-
先建好登录用的model,其次理解使用cookie和session的原理,一个在本机保存,一个在服务器保存
-
编写views中login的函数
def login(request):
username_get = request.POST['name']
password_get = request.POST['password']
b=[]
a = 0
b = UserInfo.objects.filter(username=username_get)
a = len(b)
if a==0:
return HttpResponse("0")
else:
if request.method == 'POST':
#return HttpResponse(result)
if b[0].password==password_get:
display ='none'
displaytwo='block'
username = username_get
logined = False
template = get_template('one/default.html')
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
response = HttpResponse(html)
try:
if username_get:
request.session['name'] = username_get #使用session来保存用户登录信息
#response.set_cookie('name',username_get) #使用response(用户自己电脑)保存的cookie来验证用户登录
if password_get:
request.session['password'] = password_get
#response.set_cookie('password',password_get)
except:
pass
return response
else:
return HttpResponse("0")
- login主要的用户第一次登录时,需要调用的,包括去POST中的值并验证,同时保存在cookie或session中
if 'name' in request.session and 'password' in request.session:#判断是否有登录过,并是否有效
username = request.session['name']
d['display'] = 'none'
d['displaytwo'] = 'block'
logined = False#有效就把登录和注册的按钮不显示
c['d'] = d #c是个字典,
template = get_template('one/default.html')
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)
- 使用session保存,即使用户在浏览器清除了cookie,重新刷新,登录信息仍然有效