在之前的帖子中,介绍了在Django中如何手动设置cookie,由于cookis存储在客户端,对于帐户安全要求严格的应用来说,
存储在客户端显然不是上策,故而需要session,由于session是存储在服务端,安全较session高,本贴接上继续session设置。关键代码如下:
In my views.py
1 def login(request): 2 context={} 3 if request.method=='GET': 4 return render(request,'login.html',context) 5 else: 6 username=request.POST.get('username') 7 password=request.POST.get('password') 8 user = Account.objects.filter(username__exact=username,password__exact=password) 9 10 #session 的设置 11 if user.exists(): 12 request.session['username']=username 13 return redirect(to='contact') 14 else: 15 return HttpResponse("Login failed,please go back to try it again")
1 def contact(request): 2 context={} 3 #get session 4 username=request.session.get('username','') 5 if username: 6 context['username']=username 7 return render(request,'contact.html',context) 8 else: 9 return render(request,'tologin.html',context)
1 def logout(request): 2 context={} 3 #删除session 4 del request.session['username'] 5 return redirect(to='login')