您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章将为大家详细讲解有关使用Django框架怎么实现首页和登录页分离,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
1.登录模板login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<form method="post">
<p>用户名:<input type="text" name="username"></p>
<p>密码:<input type="password" name="pwd"></p>
<p><input type="submit" value="提交"></p>
<hr>
</form>
<p> {{ result }}</p>
</body>
</html>2.URL设置

url(r'^login/', "hello.views.login")
表示浏览器访问login,就指向hello应用下views文件下login方法
3.在login方法下响应login模板和完成登录功能
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其中我们使用了UserLogin类,并用此类中的方法完成了用户是否已经登录的验证。
UserClass.py:
# coding:utf-8 class UserLogin: userName = '' pwd = '' # 构造方法 def __init__(self,username,pwd): self.userName = username self.pwd = pwd # 登录验证方法 def isLogin(self): if self.userName == 'jack' and self.pwd == '123': return True else: return False
在views.py中使用之前必须要引入:
from UserClass import UserLogin
表示从UserClass中导入UserLogin。
4.在login方法中,登录成功就跳转到了首页,首页显示登录用户名
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h3>这是首页,当前登录用户是:{{ username }}</h3>
<p><a href="##" rel="external nofollow" >安装退出</a></p>
</body>
</html>def hi(request):
msg = {'username':'游客'}
if request.COOKIES.get('userlogin_username') != None :
msg['username'] = request.COOKIES.get('userlogin_username')
myReponse = render_to_response("index.html",msg)
return myReponse关于使用Django框架怎么实现首页和登录页分离就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。