|
逻辑
注册
登录 ---- 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'),
|
|