侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

框架(架构)  /  管理员 发布于 7年前   258

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

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

from django import formsfrom django.contrib.auth.models import Userfrom 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 authfrom django.contrib import messagesfrom django.template.context import RequestContext from django.forms.formsets import formset_factoryfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from bootstrap_toolkit.widgets import BootstrapUneditableInputfrom 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="https://html5shim.googlecode.com/svn/trunk/html5.js"></script>  <![endif]-->  <script src="https://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="https:contactme/" rel="external nofollow" rel="external nofollow" ><input type="button" value="忘记密码" class="btn btn-danger"></a>        <a href="https: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/,出现如下登陆界面:


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


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


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

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

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

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

urls.py里添加:

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

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


  • 上一条:
    django用户登录和注销的实现方法
    下一条:
    django缓存配置的几种方法详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Filament v3.1版本发布(0个评论)
    • docker + gitea搭建一个git服务器流程步骤(0个评论)
    • websocket的三种架构方式使用优缺点浅析(0个评论)
    • ubuntu20.4系统中宿主机安装nginx服务,docker容器中安装php8.2实现运行laravel10框架网站(0个评论)
    • phpstudy_pro(小皮面板)中安装最新php8.2.9版本流程步骤(0个评论)
    • 近期文章
    • 在go语言中实现字符串可逆性压缩及解压缩功能(0个评论)
    • 使用go + gin + jwt + qrcode实现网站生成登录二维码在app中扫码登录功能(0个评论)
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-05
    • 2020-02
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-11
    • 2021-03
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-08
    • 2023-08
    • 2023-10
    • 2023-12
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客