cookie实现访问index无法访问必须从login走,返回固定的session值,
一个浏览器登陆之后会保存用户名密码,可以直接访问index,换个浏览器访问index就无法访问
urls
from django.conf.urls import url from django.contrib import admin from app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'login',views.login), url(r'index',views.index), ]
views
from django.shortcuts import render,redirect # Create your views here. def login(req): print("COOKIES",req.COOKIES) if req.method=="POST": name=req.POST.get("user") pwd=req.POST.get("pwd") if name=="tom"and pwd==123: ret=redirect("index.html") ret.set_cookie("username","name") return ret return render(req,"login.html") def index(req): if req.COOKIES.get("username",None)=="name": name="tom" return render(req,"index.html",locals()) else: return redirect("login.html")
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{ name }}</h1> </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="login" method="post"> <p>姓名<input type="text"name="user"></p> <p>密码<input type="password"name="pwd"></p> <p><input type="submit"></p> </form> </body> </html>