Django登錄邏輯,中間用到Cookie創建、讀取、刪除、等操作


 1 #-*- coding utf-8 -*-
 2 from django.shortcuts import render,render_to_response
 3 from django.http import HttpResponse,HttpResponseRedirect
 4 from django.template import RequestContext
 5 from django import forms
 6 from models import User
 7 
 8 #表單
 9 class UserForm(forms.Form): 
10     username = forms.CharField(label='用戶名',max_length=100)
11     password = forms.CharField(label='密碼',widget=forms.PasswordInput())
12 
13 
14 #注冊
15 def regist(req):
16     if req.method == 'POST':
17         uf = UserForm(req.POST)
18         if uf.is_valid():
19             #獲得表單數據
20             username = uf.cleaned_data['username']
21             password = uf.cleaned_data['password']
22             #添加到數據庫
23             User.objects.create(username= username,password=password)
24             return HttpResponse('regist success!!')
25     else:
26         uf = UserForm()
27     return render_to_response('regist.html',{'uf':uf}, context_instance=RequestContext(req))
28 
29 #登陸
30 def login(req):
31     if req.method == 'POST':
32         uf = UserForm(req.POST)
33         if uf.is_valid():
34             #獲取表單用戶密碼
35             username = uf.cleaned_data['username']
36             password = uf.cleaned_data['password']
37             #獲取的表單數據與數據庫進行比較
38             user = User.objects.filter(username__exact = username,password__exact = password)
39             if user:
40                 #比較成功,跳轉index
41                 response = HttpResponseRedirect('/online/index/')
42                 #將username寫入瀏覽器cookie,失效時間為3600
43                 response.set_cookie('username',username,3600)
44                 return response
45             else:
46                 #比較失敗,還在login
47                 return HttpResponseRedirect('/online/login/')
48     else:
49         uf = UserForm()
50     return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))
51 
52 #登陸成功
53 def index(req):
54     username = req.COOKIES.get('username','')
55     return render_to_response('index.html' ,{'username':username})
56 
57 #退出
58 def logout(req):
59     response = HttpResponse('logout !!')
60     #清理cookie里保存username
61     response.delete_cookie('username')
62     return response
63 復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM