Django实战之用户认证(用户登录与注销)


Posted in Python onJuly 16, 2018

上一篇中,我们已经打开了Django自带的用户认证模块,并配置了数据库连接,创建了相应的表,本篇我们将在Django自带的用户认证的基础上,实现自己个性化的用户登录和注销模块。

首先,我们自己定义一个用户登录表单(forms.py):

from django import forms
from django.contrib.auth.models import User
from bootstrap_toolkit.widgets import BootstrapDateInput, BootstrapTextInput, BootstrapUneditableInput
 
class LoginForm(forms.Form):
  username = forms.CharField(
    required=True,
    label=u"用户名",
    error_messages={'required': '请输入用户名'},
    widget=forms.TextInput(
      attrs={
        'placeholder':u"用户名",
      }
    ),
  )  
  password = forms.CharField(
    required=True,
    label=u"密码",
    error_messages={'required': u'请输入密码'},
    widget=forms.PasswordInput(
      attrs={
        'placeholder':u"密码",
      }
    ),
  )  
  def clean(self):
    if not self.is_valid():
      raise forms.ValidationError(u"用户名和密码为必填项")
    else:
      cleaned_data = super(LoginForm, self).clean()

我们定义的用户登录表单有两个域username和password,这两个域都为必填项。

接下来,我们定义用户登录视图(views.py),在该视图里实例化之前定义的用户登录表单

from django.shortcuts import render_to_response,render,get_object_or_404 
from django.http import HttpResponse, HttpResponseRedirect 
from django.contrib.auth.models import User 
from django.contrib import auth
from django.contrib import messages
from django.template.context import RequestContext
 
from django.forms.formsets import formset_factory
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
 
from bootstrap_toolkit.widgets import BootstrapUneditableInput
from django.contrib.auth.decorators import login_required
 
from .forms import LoginForm
 
def login(request):
  if request.method == 'GET':
    form = LoginForm()
    return render_to_response('login.html', RequestContext(request, {'form': form,}))
  else:
    form = LoginForm(request.POST)
    if form.is_valid():
      username = request.POST.get('username', '')
      password = request.POST.get('password', '')
      user = auth.authenticate(username=username, password=password)
      if user is not None and user.is_active:
        auth.login(request, user)
        return render_to_response('index.html', RequestContext(request))
      else:
        return render_to_response('login.html', RequestContext(request, {'form': form,'password_is_wrong':True}))
    else:
      return render_to_response('login.html', RequestContext(request, {'form': form,}))

该视图实例化了之前定义的LoginForm,它的主要业务逻辑是:

1. 判断必填项用户名和密码是否为空,如果为空,提示"用户名和密码为必填项”的错误信息

2. 判断用户名和密码是否正确,如果错误,提示“用户名或密码错误"的错误信息

3. 登陆成功后,进入主页(index.html)

其中,登录页面的模板(login.html)定义如下:

<!DOCTYPE html>
{% load bootstrap_toolkit %}
{% load url from future %}
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>数据库脚本发布系统</title>
  <meta name="description" content="">
  <meta name="author" content="朱显杰">
  {% bootstrap_stylesheet_tag %}
  {% bootstrap_stylesheet_tag "responsive" %}
  <style type="text/css">
    body {
      padding-top: 60px;
    }
  </style>
  <!--[if lt IE 9]>
  <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
  {% bootstrap_javascript_tag %}
  {% block extra_head %}{% endblock %}
</head>
 
<body>
 
  {% if password_is_wrong %}
    <div class="alert alert-error">
      <button type="button" class="close" data-dismiss="alert">×</button>
      <h4>错误!</h4>用户名或密码错误
    </div>
  {% endif %}  
  <div class="well">
    <h1>数据库脚本发布系统</h1>
    <p> </p>
    <form class="form-horizontal" action="" method="post">
      {% csrf_token %}
      {{ form|as_bootstrap:"horizontal" }}
      <p class="form-actions">
        <input type="submit" value="登录" class="btn btn-primary">
        <a href="/contactme/" rel="external nofollow" rel="external nofollow" ><input type="button" value="忘记密码" class="btn btn-danger"></a>
        <a href="/contactme/" rel="external nofollow" rel="external nofollow" ><input type="button" value="新员工?" class="btn btn-success"></a>
      </p>
    </form>
  </div>
 
</body>
</html>

最后还需要在urls.py里添加:

(r'^accounts/login/$', 'dbrelease_app.views.login'),

最终的效果如下:

1)当在浏览器里输入http://192.168.1.16:8000/accounts/login/,出现如下登陆界面:

Django实战之用户认证(用户登录与注销)

2)当用户名或密码为空时,提示”用户名和密码为必填项",如下所示:

Django实战之用户认证(用户登录与注销)

3)当用户名或密码错误时,提示“用户名或密码错误",如下所示:

Django实战之用户认证(用户登录与注销)

4)如果用户名和密码都正确,进入主页(index.html)。

既然有login,当然要有logout,logout比较简单,直接调用Django自带用户认证系统的logout,然后返回登录界面,具体如下(views.py):

@login_required
def logout(request):
  auth.logout(request)
  return HttpResponseRedirect("/accounts/login/")

上面@login_required表示只有用户在登录的情况下才能调用该视图,否则将自动重定向至登录页面。

urls.py里添加:

(r'^accounts/logout/$', 'dbrelease_app.views.logout'),

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python中self原理实例分析
Apr 30 Python
使用python检测主机存活端口及检查存活主机
Oct 12 Python
举例讲解Python面向对象编程中类的继承
Jun 17 Python
python类:class创建、数据方法属性及访问控制详解
Jul 25 Python
利用Python实现颜色色值转换的小工具
Oct 27 Python
解决python3在anaconda下安装caffe失败的问题
Jun 15 Python
pandas数据处理基础之筛选指定行或者指定列的数据
May 03 Python
解决python写入带有中文的字符到文件错误的问题
Jan 31 Python
如何运行.ipynb文件的图文讲解
Jun 27 Python
使用Python函数进行模块化的实现
Nov 15 Python
Python中requests做接口测试的方法
May 30 Python
Python中的变量与常量
Nov 11 Python
Python3数据库操作包pymysql的操作方法
Jul 16 #Python
django缓存配置的几种方法详解
Jul 16 #Python
Python 字符串与数字输出方法
Jul 16 #Python
Django实战之用户认证(初始配置)
Jul 16 #Python
python format 格式化输出方法
Jul 16 #Python
Python合并多个Excel数据的方法
Jul 16 #Python
详解django.contirb.auth-认证
Jul 16 #Python
You might like
数字转英文
2006/12/06 PHP
PHP设计模式之调解者模式的深入解析
2013/06/13 PHP
PHP中提问频率最高的11个面试题和答案
2014/09/02 PHP
PHP连接和操作MySQL数据库基础教程
2014/09/29 PHP
PHP生成网站桌面快捷方式代码分享
2014/10/11 PHP
教你如何开启shopnc b2b2c 伪静态
2014/10/21 PHP
PHP查询快递信息的方法
2015/03/07 PHP
php格式化时间戳
2016/12/17 PHP
PHP基于双向链表与排序操作实现的会员排名功能示例
2017/12/26 PHP
网页里控制图片大小的相关代码
2006/06/25 Javascript
图片格式的JavaScript和CSS速查手册
2007/08/20 Javascript
JavaScript 异步调用框架 (Part 4 - 链式调用)
2009/08/04 Javascript
checkbox全选/取消全选以及checkbox遍历jQuery实现代码
2009/12/02 Javascript
JavaScript Ajax Json实现上下级下拉框联动效果实例代码
2013/11/23 Javascript
jquery插件star-rating.js实现星级评分特效
2015/04/15 Javascript
jQuery中判断对象是否存在的方法汇总
2016/02/24 Javascript
jQuery插件扩展操作入门示例
2017/01/16 Javascript
js+html5实现侧滑页面效果
2017/07/15 Javascript
使用3D引擎threeJS实现星空粒子移动效果
2020/09/13 Javascript
React Router v4 入坑指南(小结)
2018/04/08 Javascript
vue中的模态对话框组件实现过程
2018/05/01 Javascript
vue mounted组件的使用
2018/06/18 Javascript
js实现延迟加载的几种方法详解
2019/01/19 Javascript
微信小程序封装分享与分销功能过程解析
2019/08/13 Javascript
使用vue打包进行云服务器上传的问题
2020/03/02 Javascript
解决VueCil代理本地proxytable无效报错404的问题
2020/11/07 Javascript
Python多线程、异步+多进程爬虫实现代码
2016/02/17 Python
Python enumerate索引迭代代码解析
2018/01/19 Python
python使用socket创建tcp服务器和客户端
2018/04/12 Python
解决python ogr shp字段写入中文乱码的问题
2018/12/31 Python
python ChainMap的使用和说明详解
2019/06/11 Python
django框架使用views.py的函数对表进行增删改查内容操作详解【models.py中表的创建、views.py中函数的使用,基于对象的跨表查询】
2019/12/12 Python
一个基于canvas的移动端图片编辑器的实现
2020/10/28 HTML / CSS
国际会议邀请函范文
2014/01/16 职场文书
医院保洁服务方案
2014/06/11 职场文书
Spring 使用注解开发
2022/05/20 Java/Android