Django框架首页和登录页分离操作示例

yipeiwu_com6年前Python基础

本文实例讲述了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>
  <h2>这是首页,当前登录用户是:{{ username }}</h2>
  <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框架的Python程序设计有所帮助。

相关文章

python使用rpc框架gRPC的方法

概述 gRPC 是谷歌开源的一个rpc(远程程序调用)框架,可以轻松实现跨语言,跨平台编程,其采用gRPC协议(基于HTTP2)。 rpc: remote procedure call...

Windows中安装使用Virtualenv来创建独立Python环境

Windows中安装使用Virtualenv来创建独立Python环境

0、什么时候会用到virtualenv? 假设系统中的两个应用,其中A应用对库LibFoo的版本要求为1,而B应用对同一个库LibFoo的版本要求为2,两个应用对同一个库的要求想冲突了,...

Python中Django框架下的staticfiles使用简介

django1.3新加入了一个静态资源管理的app,django.contrib.staticfiles。在以往的django版本中,静态资源的管理一向都是个问题。部分app发布的时候会...

python2.7安装图文教程

python2.7安装图文教程

Python安装过程,供大家参考,具体内容如下 1.下载安装程序 我们安装Python的一个重要目的是为了用IAR编译CC2640 OAD文件时执行合并文件的脚本,所以我们一起来看看Py...

Python利用正则表达式实现计算器算法思路解析

  (1)不使用eval()等系统自带的计算方法   (2)实现四则混合运算、括号优先级解析 思路:   1、字符串预处理,将所有空格去除   2、判断是否存在括号运算,若存在进行第3步...