邏輯
註冊
登錄 ---- index --- logout
views.py
from django import forms from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render_to_response from models import User class UserForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def regist(req): #註冊 if req.method == 'POST': uf = UserForm(req.POST) if uf.is_valid(): username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] User.objects.create(username = username ,password = password) print username,password return HttpResponseRedirect('/login/') #跳轉到那個路徑 else: uf = UserForm() return render_to_response('regist.html',{'uf':uf}) def login(req): #登錄 if req.method == 'POST': uf = UserForm(req.POST) if uf.is_valid(): username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] users = User.objects.filter(username = username ,password = password) #數據庫搜素,如果users對象不爲空,代表搜索成功 if users: response = HttpResponseRedirect('/index/') #生成response對象設置cookie,cookie爲字典 response.set_cookie('username',username,3600) return response #把username傳給下個頁面 else: return HttpResponseRedirect('/login/') else: uf = UserForm() return render_to_response('login.html',{'uf':uf}) def index(req): username = req.COOKIES.get('username','') #讀取cookie return render_to_response('index.html',{'username':username}) def logout(req): response = HttpResponse('logout') response.delete_cookie('username') return response
models.py
from django.db import models class User(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=200) def __unicode__(self): return self.username
templates/regist.html
<html>
<head>
</head>
<body>
<form method='post'>
`uf`.`as_p`
<input type='submit' value='ok'/>
</form>
</body>
</html>
templates/index.html
<html>
<head>
</head>
<body>
<div>
<h1>welcome `username`</h1>
<a href='/logout/'>logout</a>
</div>
</body>
</html>
templates/login.html
<html>
<head>
</head>
<body>
<form method='post'>
`uf`.`as_p`
<input type='submit' value='ok'/>
</form>
</body>
</html>
urls.py
url(r'^admin/', include(admin.site.urls)), url(r'^regist/$','blog.views.regist'), url(r'^login/$','blog.views.login'), url(r'^index/$','blog.views.index'), url(r'^logout/$','blog.views.logout'),