Django会话之cookie

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django会话之cookie相关的知识,希望对你有一定的参考价值。

In 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 = authenticate(username=username, password=password) 
 9         if user is not None and user.is_active:
10             response=redirect(to=contact)
11             response.set_cookie("username",username,max_age=3600)
12             return response
13         else:
14             return HttpResponse("Login failed,please go back to try it again")

1 def logout(request):
2         context={}
3         response=redirect(to=login)
4         # response=HttpResponse(‘You have logouted‘)
5         response.delete_cookie(username)
6         return response
1 def contact(request):
2     context={}
3     username=request.COOKIES.get("username",‘‘)
4     if username!=‘‘:
5         context[username]=username
6         return render(request,contact.html,context)
7     else:
8         return HttpResponse("Please login first")

 

 

以上是关于Django会话之cookie的主要内容,如果未能解决你的问题,请参考以下文章

Django之cookie与session

Django之cookie and session

Django之cookie 与session组件

Django会话,用户和注册之cookie

Django之Session与Cookie

Django基础之cookie