URL :
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^login/', views.login), url(r'^home/', views.home), url(r'^index/', views.index), ]
前端 :
<form action="" method="post"> {% csrf_token %} <input type="text" name="name"> <input type="password" name="pwd"> <input type="submit"> </form>
Cookie视图 :
from django.shortcuts import render,redirect,HttpResponse #装饰器 def login_required(fn): def inner(request, *args, **kwargs): if request.COOKIES.get("login") != "1": next = request.path_info #未登录用户访问无权限的页面, 获取所访问的url, 以便登陆后直接跳转 return redirect("/login/?next={}".format(next)) #将所获取的url参数传递到登录页面的url上 ret = fn(request, *args, **kwargs) return ret return inner #登录页面 def login(request): if request.method == "POST": user = request.POST.get("name") pwd = request.POST.get("pwd") if user == "dong" and pwd == "dong": next = request.GET.get("next") #在登陆页面的url上获取未登录用户访问无权限页面所传递的参数 if next: #如果有参数 ret = redirect(next) else: #没有参数 ret = redirect("/home/") #没有参数说明用户未访问无权限页面,直接登录 ret.set_cookie("login", "1") return ret return render(request, "login.html") @login_required def home(request): return HttpResponse("home页面") @login_required def index(request): return HttpResponse("index")
Session视图 :
#装饰器 def login_required(fn): def inner(request, *args, **kwargs): if request.session.get("login") != "1": next = request.path_info #未登录用户访问无权限的页面, 获取所访问的url, 以便登陆后直接跳转 return redirect("/login/?next={}".format(next)) #将所获取的url参数传递到登录页面的url上 ret = fn(request, *args, **kwargs) return ret return inner #登录页面 def login(request): if request.method == "POST": user = request.POST.get("name") pwd = request.POST.get("pwd") if user == "dong" and pwd == "dong": request.session["login"] = "1" #设置session,自动传递 next = request.GET.get("next") #在登陆页面的url上获取未登录用户访问无权限页面所传递的参数 if next: #如果有参数 return redirect(next) else: #没有参数 return redirect("/home/") #没有参数说明用户未访问无权限页面,直接登录 # ret.set_cookie("login", "1") # return ret return render(request, "login.html") @login_required def home(request): return HttpResponse("home页面") @login_required def index(request): return HttpResponse("index")