Django实战之用户认证(用户登录与注销)
作者:Zhu_Julian 发布时间:2023-03-23 16:52:26
上一篇中,我们已经打开了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/,出现如下登陆界面:
2)当用户名或密码为空时,提示”用户名和密码为必填项",如下所示:
3)当用户名或密码错误时,提示“用户名或密码错误",如下所示:
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'),
来源:https://blog.csdn.net/dbanote/article/details/11465447


猜你喜欢
- 一、pycharm配置1、部署配置工具==》部署==》配置2、python解释器文件==》设置==》项目:xx==》python解释器3、运
- 升级背景:为了解决mysql低版本的漏洞,从mysql5.5升级到了8.0.11版本,再次升级到了8.0.17版本(从版本是2019.7.2
- 程序需要多进程见共享内存,使用了Manager的dict。最初代码如下:from multiprocessing import Proces
- Mysql迁移历史数据记录一下工作中由于业务需要以及系统的数据库模型变更,导致需要做一下历史数据迁移的解决办法需求陈述一共涉及到三张表,分别
- 本文实例讲述了Python实现链表反转的方法。分享给大家供大家参考,具体如下:Python实现链表反转链表反转(while迭代实现):链表的
- 今天在推上看到一条获取PHP类私有属性的推文,感觉很有意思:顺着推文联想,还有其他方式吗?经过自己的测试及网上答案,总结出三种方法:1. 反
- 相信大家对于常见 CSS BUG 的处理已经相对比较熟悉,例如:IE6 Three Pixel Gap、IE5/6 Doubled Floa
- 我就废话不多说了,直接上代码吧!# -*- coding: UTF-8 -*-import osimport report = 8080de
- 文章介绍内容以Python 3.x版本为主一、for循环语句程序一般情况下都是按顺序执行代码,在代码执行过程中,会有复杂的语句,这个时候循环
- golang并没有像C语言一样提供三元表达式。三元表达式的好处是可以用一行代码解决原本需要多行代码才能完成的功能,让冗长的代码瞬间变得简洁。
- 在广大网友心目中,他们就是中国互联网搜索领域的三驾马车。无论这三家搜索巨头承不承认,在网友眼中总会来将他们进行对比比较。当然,更多时候的比较
- 微信小程序中的云开发想必大家还不是很熟悉,因为云开发也就是9月份上线的,相比之前大家对于数据库的存储都是用的是自己的服务器,接下来这篇文章主
- 大家觉得在接手遗留代码时,见到什么东东是最让人感到不耐烦的?复杂无比的 UML ?我觉得不是。我的答案是,超过两个 else 的 if ,或
- 前言由于今年暑假在学习一些自然语言处理的东西,发现网上对k-means的讲解不是很清楚,网上大多数代码只是将聚类结果以图片的形式呈现,而不是
- 一、利用Google API生成二维码Google提供了较为完善的二维码生成接口,调用API接口很简单,以下是调用代码:$urlToEnco
- 修改配置文件:vim /usr/local/php/etc/php.ini[Phar]phar.readonly = Off压缩:a. 创建
- 该代码用的是paramiko模块,python版本是python2.7下面上源码# -*- coding: utf-8 -*-import
- 什么是CSS裸奔节?CSS裸奔节就是将这整站的css样式都去掉,这样所有的布局,颜色,背景什么的就都没有了(除非你使用table布局),只剩
- 1、pyqtgraph库数据可视化效果还不错,特别是窗体程序中图像交互性较好;安装也很方便,用 pip 安装。2、在Python中新建一个
- 找到对应页面,将Reopen last project on startup前面的勾去掉来源:https://blog.csdn.net/l