标签: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), ]
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/")
<!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>
<!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>
标签:post app inpu pwd use charset http 主页 ssi
原文地址:http://www.cnblogs.com/Neeo/p/7639881.html