码迷,mamicode.com
首页 > 其他好文 > 详细

Django #cookie

时间:2017-09-24 14:28:58      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:utf-8   examples   https   out   request   charset   return   val   .com   

views.py

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.
user_info = {
    admin:{pwd:111111},
    user2:{pwd:123123}
}
def login(request):
    if request.method ==GET:
        return render(request,login.html)  #请求login.index的页面渲染。usl还是http://127.0.0.1:8000/login/
    if request.method ==POST:
        u = request.POST.get(username)
        p = request.POST.get(pwd)
        dic=user_info.get(u)
        if not dic:
            return render(request,login.html) #请求login.index的页面渲染。usl还是http://127.0.0.1:8000/login/login.html
        if dic[pwd]==p:
            res = redirect(/index/)        #重定向,请求的Url变成http://127.0.0.1:8000/index/
            res.set_cookie(username,u)
            return res
        else:
            return render(request,login.html)

def index(request):
    v = request.COOKIES.get(username)
    if not v:
        return redirect(/login/)           #重定向,请求的Url变成http://127.0.0.1:8000/login/
    else:
        return render(request,index.html,{current_user:v})

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="login.html" method="POST">
        <input type="text" name=‘username‘ placeholder="用户名">
        <input type="text" name=‘pwd‘ placeholder="密码">
        <input type="submit" value="登录">
        <input type="button" value="提交">

    </form>

</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>Welcome {{ current_user }}</p>
</body>
</html>

urls.py

"""lwslws URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r‘^$‘, views.home, name=‘home‘)
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r‘^$‘, Home.as_view(), name=‘home‘)
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r‘^blog/‘, include(‘blog.urls‘))
"""
from django.conf.urls import url
from django.contrib import admin
from apps01 import views

urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^login/, views.login),
    url(r^index/, views.index),
]

 

浏览器展示:

技术分享

 

Django #cookie

标签:utf-8   examples   https   out   request   charset   return   val   .com   

原文地址:http://www.cnblogs.com/lwsup/p/7586987.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!