Django框架用户注销功能实现方法分析
程序员文章站
2023-08-12 08:11:06
本文实例讲述了django框架用户注销功能实现方法。分享给大家供大家参考,具体如下:
httpresponse()里有个delete_cookie()方法专门用来删除co...
本文实例讲述了django框架用户注销功能实现方法。分享给大家供大家参考,具体如下:
httpresponse()
里有个delete_cookie()
方法专门用来删除cookie
我们到此来完整的实现一下:访问首页如果没有登录,就跳转到登录页面,登录成功之后再跳转回来的过程。
3个方法,index、login、logout
# coding:utf-8 from django.shortcuts import render,render_to_response # create your views here. from django.http import httpresponse from userclass import userlogin def index(request): msg = {'username':'guest'} if request.cookies.get('userlogin_username') != none : msg['username'] = request.cookies.get('userlogin_username') myreponse = render_to_response("index.html",msg) return myreponse def login(request): msg = {'result': ''} if request.method == 'post': getusername = request.post.get('username') getpwd = request.post.get('pwd') # 实例化userlogin类 loginobj = userlogin(getusername,getpwd) if loginobj.islogin(): myreponse = httpresponse("<script>self.location='/index'</script>") myreponse.set_cookie('userlogin_username',getusername,3600) return myreponse else: msg['result'] = '用户名或密码错误' myreponse = render_to_response("login.html", msg) return myreponse # 用户注销 def logout(request): r = httpresponse() r.delete_cookie('userlogin_username') r.write("<script>self.location='/index'</script>") return r
首页模板index.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>首页</title> </head> <body> <h2>这是首页,当前登录用户是:{{ username }}</h2> {% ifequal username "guest" %} <p><a href="/login" rel="external nofollow" >登录</a></p> {% else %} <p><a href="/logout" rel="external nofollow" >安装退出</a></p> {% endifequal %} </body> </html>
其中用到了django的模板语法
希望本文所述对大家基于django框架的python程序设计有所帮助。
下一篇: Django框架首页和登录页分离操作示例