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

cookie-session

时间:2017-10-09 10:52:39      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:post   app   inpu   pwd   use   charset   http   主页   ssi   

Django的cookie与session

cookie

通过示例来演示基于cookie的登录

技术分享
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^index/, views.index),
    url(r^login/, views.login),
]
urls.py

 

技术分享
from django.shortcuts import render, redirect


def login(request):
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get(pwd)
        if user == "wang" and pwd == "666":
            red = redirect("/index/")  # 登陆成功,跳转到主页
            red.set_cookie("username", user)  # 将用户名插入到cookie
            return red
        else:
            return render(request, "login.html")
    else:
        return render(request, "login.html")


def index(request):
    user = request.COOKIES.get("username")
    if user:
        return render(request, "index.html", {"user": user})
    else:
        return redirect("/login/")
views.py

 

技术分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>login</title>
</head>
<body>
<form action="/login/" method="post">
    {% csrf_token %}
    <input type="text" name="user" id="">
    <input type="password" name="pwd" id="">
    <input type="submit" id="确定">
</form>
</body>
</html>
login.html

 

技术分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>index</title>
</head>
<body>
<h1>欢迎:{{ user }}</h1>
</body>
</html>
index.html

 

cookie-session

标签:post   app   inpu   pwd   use   charset   http   主页   ssi   

原文地址:http://www.cnblogs.com/Neeo/p/7639881.html

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