[Django]SE项目回忆录(二)-注册/登录功能的实现及细节

该项目中提供了注册和登录两部分功能,功能描述如下:

注册:
允许任何用户进行学生身份的注册。
教师用户预先已经保存在数据库中,不允许以游客身份注册新的教师用户。
注册时需要填写的信息包括:
- 用户名
- 密码(确认密码)
- 邮箱

登录:
允许教师和学生两类用户组中的用户进行登录。
登录时需要填写的信息包括:
- 用户名
- 密码
登录成功后,根据不同用户所属的用户组,进入相应的页面。


第一部分 注册功能

首先贴上注册部分的views代码片:

@csrf_protect
def student_register(request):  errors= []  account=None  password=None  password2=None  email=None  CompareFlag=False  if request.method == 'POST':  if not request.POST.get('account'):  errors.append('Please Enter account')  else:  account = request.POST.get('account')  if not request.POST.get('password'):  errors.append('Please Enter password')  else:  password = request.POST.get('password')if not request.POST.get('password2'):  errors.append('Please Enter password2')  else:  password2 = request.POST.get('password2')  if not request.POST.get('email'):  errors.append('Please Enter email')  else:  email = request.POST.get('email')if password is not None and password2 is not None:  if password == password2:  CompareFlag = True  else :  errors.append('password2 is diff password ')  if account is not None and password is not None and password2 is not None and email is not None and CompareFlag :  if User.objects.filter(username=account):errors.append('this account already exists, Please change another username')else:user=User.objects.create_user(account,email,password) user.is_active=Truepermission=Permission.objects.get(name='student')user.user_permissions.add(permission)user.save()return HttpResponseRedirect('../../')return render_to_response('account/register.html', {'errors': errors}, context_instance=RequestContext(request))  

水平不足,代码十分简陋,此处只对当时感到困惑的一些问题进行说明了。

Q1:如何返回带有form(表单)的页面

根据Django框架的设定,访问某url时,首先调用views中对应函数,根据函数返回值传回相应contexthtml。大多数使用form元素时,是为了使用post/get的方法向网站传回表单中的数据。但是在初次访问该页面时,没有表单提交的请求,所以在views中的处理函数中如果直接写处理表单数据的代码,系统会报错,因为函数无法从get请求中获取到所需的数据进行相应的操作。
会发生这个问题的原因是对网站逻辑了解模糊,敲代码时关注了提交表单后的数据处理,却忽略了首次访问时如何进入界面的问题。
解决办法是:

views函数中对数据进行处理前先进行逻辑判断,“请求头里面是否有该数据”,没有的话返回原页面,并且提示相应信息。

代码实现:

if request.method == 'POST':  if not request.POST.get('account'):  errors.append('Please Enter account')  else:  account = request.POST.get('account')  if not request.POST.get('password'):  errors.append('Please Enter password')  else:  password = request.POST.get('password')if not request.POST.get('password2'):  errors.append('Please Enter password2')  else:  password2 = request.POST.get('password2')  if not request.POST.get('email'):  errors.append('Please Enter email')  else:  email = request.POST.get('email')if password is not None and password2 is not None:  if password == password2:  CompareFlag = True  else :  errors.append('password2 is diff password ')  
return render_to_response('account/register.html', {'errors': errors}, context_instance=RequestContext(request))

第二部分 登陆功能

登录部分代码片:

@csrf_protect
def alogin(request):errors=[]account=Nonepassword=Noneif request.user.is_authenticated():if request.user.has_perm('auth.is_teacher'):return HttpResponseRedirect('/update')else:return HttpResponseRedirect('/main')else:if request.method == 'POST':if not request.POST.get('account'):errors.append('Please Enter account')else:account = request.POST.get('account')if not request.POST.get('password'):errors.append('Please Enter password')else:password = request.POST.get('password')if account is not None and password is not None:user = authenticate(username=account,password=password)if user is not None:if user.is_active :login(request,user)if user.has_perm('auth.is_teacher') :return HttpResponseRedirect('/update')else:return HttpResponseRedirect('/main')else:errors.append('disabled account')else:errors.append('invalid user')return render_to_response('account/login.html',{'errors':errors}, context_instance=RequestContext(request))

Q1:用户权限管理

如上所述,用户分为教师和学生。用来区分学生和教师的方法是分别赋予两类user的user_permissions不同的值。
user_permissions也是Django框架中内置的一类模型,用于管理一个user所具有的权限。auth_user_user_permissions(即user_permission在Django框架中的名字)的table形式为:

iduser_idpermisson_id
11030
21628
xxxxx

id表示user_permission的id,user_id和permission_id即代表某个user以及该user所对应的permission有哪些,此处的permission_id为数组形式。
permission_id对应的permission又存储在auth_permission这个table中,其内容大致为:

idnamecontent_type_idcodename
1Can add log entry1add_logentry
2Can change log entry1change_logentry
3Can delete log entry1delete_logentry
4Can add permission2add_permission
5Can change permission2change_permission
6Can delete permission2delete_permission
7Can add group3add_group
8Can change group3change_group
9Can delete group3delete_group
10Can add user4add_user
11Can change user4change_user
xxxxxxxxxxxx
30teacher4is_teacher
31student4is_student

可以观察到除了30、31行比较特殊外,其余内容比较相似。是因为其他部分都是Django内部自动为每个model生成的,其中包括了内置的如user、group等。
而teacher、student两个则是此项目中手工添加的权限,可以看到,此处teacher和student两个权限的id分别为30和31,对应着前一个表格中的permission_id一列。
以上为实现权限管理功能所做的准备,以及相关数据的说明。接下来简单说一下代码部分是如何实现这个功能的。
在登录函数中,权限判断的代码如下:

if request.user.is_authenticated():if request.user.has_perm('auth.is_teacher'):return HttpResponseRedirect('/update')else:return HttpResponseRedirect('/main')

user.has_perm('xx')是user的方法之一,用来检查user.user_permission中是否有权限“xxx”存在,此处“xxx”是permission的codename(详见上面表格)。

Q2:用户认证

用户认证的部分代码如下:

if account is not None and password is not None:user = authenticate(username=account,password=password)if user is not None:if user.is_active :login(request,user)if user.has_perm('auth.is_teacher') :return HttpResponseRedirect('/update')else:return HttpResponseRedirect('/main')else:errors.append('disabled account')else:errors.append('invalid user')

其中值得我们关注的部分有:
authenticate(username,password)
user.is_active
login(request,user)
1.authenticate(username,password):该函数接受两个参数usernamepassword,如果该用户名和密码匹配,则返回该user对象;如果不匹配,则返回 None值。
2.user.is_active:是否允许用户登录, 设置为False,可以不用删除用户来禁止用户登录.
3.login(request,user):该函数接受一个HttpRequest 对象和一个 User 对象作为参数并使用Django的会话( session)框架把用户的ID保存在该会话中.

Ps:关于Django的Session框架会在后面的部分单独介绍。
Pps:csrf_protect机制及csrf框架也会在后面章节中进行说明。

转载于:https://www.cnblogs.com/rfhs/p/6852898.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/256055.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Zip4j开源jar包的简单使用

因为对项目突然要发送压缩加密的邮件附件,所以从网上看了一些资料说Zip4j开源框架比较好使,对中文的支持也比较好,所以从网上找了一个代码案例!自己写了一写,现在贴出来,方便以后想用的时候好找 1、 1 pack…

【pyqt5】——入门级模板(ui文件+ui转py文件+逻辑py文件)(消息提示框)

目录 1、ui文件 2、ui转py文件 3、逻辑py文件 4、实例 1)ui文件——demo.ui 2)ui转py文件——demo.py 3)逻辑py文件——demoLogic.py 4)运行结果 1、ui文件 这个文件是直接通过pyqt5 designer进行设计的,相关配置可见《配置Qt Design…

PCL中点特征描述子PFH、FPFH和VFH简述和示例

文章目录前言一、点特征直方图1.1 PFH1.1.1 法线估计1.1.2 特征计算1.2 FPFH1.3 VFH二、示例2.1 PFH计算2.2 FPFH2.3 VFH前言 点特征直方图是PCL中非常重要的特征描述子,在点云匹配、分割、重建等任务中起到关键作用,可以对刚体变换、点云密度和噪声均有…

BZOJ 1005: [HNOI2008]明明的烦恼

BZOJ 1005: [HNOI2008]明明的烦恼 Description 自从明明学了树的结构,就对奇怪的树产生了兴趣......给出标号为1到N的点,以及某些点最终的度数,允许在 任意两点间连线,可产生多少棵度数满足要求的树? Input 第一行为N(0 < N < 1000), 接下来N行,第i1行给出第i个节点的度…

Apache Directory 指令

<Directory> 指令 语法&#xff1a;<Directory directory-path> ... </Directory> <Directory>和</Directory>用于封装一组指令&#xff0c;使之仅对某个目录及其子目录生效。任何可以在"directory"作用域中使用的指令都可以使用。Dir…

来一个炫酷的导航条

本文分享一个带动画效果的中英文切换导航条。 鼠标放上去试一下&#xff1a; INDEX 首页 BBS 社区 HOME 我 1.用CSS3实现 效果看上去复杂&#xff0c;其实我们先来做出一个样式&#xff0c;就很简单了。如下&#xff1a; 代码&#xff1a; <nav><ul class"list…

基于C++的opencv中Mat矩阵运算方法总结

文章目录前言一、Mat运算种类1.1 代数运算1.2 类型转换前言 Mat类是目前opencv最为常用的图像数据格式&#xff0c;其优点在于无需手动开辟内存空间和实时释放&#xff0c;针对此类的各种运算方法有很多&#xff0c;本文按照各种运算方法的种类进行简单的总结和示例。 一、Mat…

【pyqt5】——信号与槽

一、简单Demo 简单使用信号和槽&#xff08;之前常用的使用方式&#xff09;&#xff1a; class DemoWin(QMainWindow):def __init__(self):super().__init__()self.initUI()def initUI(self):self.resize(400, 250)self.btn QPushButton("发送信号", self)# 发送…

JSON - 简介

JSON - 简介 JSON实例 <!DOCTYPE html> <html> <head> <meta charset"utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <h2>JavaScript 创建 JSON 对象</h2> <p> 网站名称: <spa…

mysql慢日志管理

一、日志切割 原理&#xff1a; 1、cp一个慢日志备份 2、清空原理的慢日志 3、写成脚本&#xff0c;每天一切&#xff0c;这样就ok啦 二、查找日志中的慢日志 1、做了日志切割&#xff08;慢日志文件就小了&#xff09; 2、查找某个时间的慢日志 日志时间格式&#xff1a; # Ti…

【深度学习】mask_rcnn训练自己的数据集以及模型使用(实践结合GitHub项目)

根据requirements - 开源项目默认的.txt进行库安装 环境&#xff1a;WIN10 Anoconda Pycharm python3.6.2 mask_rcnn基本流程1、训练 1)labelme进行目标物体标记&#xff0c;生成json文件&#xff0c;含点坐标、以及各个物体的标签label; json文件的格式&#xff1a;&…

EXCEL小技巧:如何统计非空单元格

http://club.excelhome.net/thread-1187271-1-1.html 下面教大家如果用函数统计非空单元格的数量 首先我们来介绍几个统计函数&#xff1a; 1.COUNT(value1,value2,...) 统计包含数字的单元格个数 2.COUNTA(value1,value2,...) 统计非空单元格的个数 3.COUNTBLANK(range&…

easyui 页签

昨天开始搭后台框架&#xff0c;到晚上的时候遇到了一个现在觉得挺可笑但是当时一直很纠结很纠结的问题&#xff0c;这个问题刚刚解决出来&#xff0c;把它拿出来说说&#xff0c;让自己长点儿记性&#xff0c;希望大家不要犯我这个错误啊 在backstage.jsp页面中我写了一个方法…

未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序。

报错信息&#xff1a; 解决方案&#xff1a; 1、“设置应用程序池默认属性”/“常规”/”启用32位应用程序”&#xff0c;设置为 true。 如下图所示&#xff1a;&#xff08;已测试&#xff0c;好使&#xff09; 方法二&#xff1a;生成->配置管理器->平台->点击Any C…

UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figur

“UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure”在利用mask_rcnn进行物体检测的时候出现的问题&#xff0c;主要是因为matplotlib的使用格式不对 可以检查者两个地方&#xff1a; 1、visualize.py中 import mat…

008. 限制上传文件的大小

第一种方法: 利用web.config的配置文件项, 进行设置; 前端aspx示例: <% Page Language"C#" AutoEventWireup"true" CodeFile"sendOutEmail.aspx.cs" Inherits"sendOutEmail" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHT…

查询实例及其代码

一、 设有一数据库&#xff0c;包括四个表&#xff1a;学生表&#xff08;Student&#xff09;、课程表&#xff08;Course&#xff09;、成绩表&#xff08;Score&#xff09;以及教师信息表&#xff08;Teacher&#xff09;。四个表的结构分别如表1-1的表&#xf…

pyinstaller打包执行exe出现“ModuleNotFoundError: No module named ‘scipy.spatial.transform._rotation_group”

这个是因为打包后的第三方库中缺少了pyd文件 具体的解决方法&#xff1a; 去环境下找到相应的py文件&#xff0c;根据https://blog.csdn.net/qq_41007606/article/details/109565069文章写的方法&#xff0c;将py编译成pyd文件&#xff0c;然后将pyd文件复制到dist相应的第三…

浙江中医药大学第十一届程序设计竞赛题解

官方题解&#xff1a;http://www.jnxxhzz.com/Article/article/9.html 2019: 特产 Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 548 Solved: 154[Submit][Status][Web Board]Description Input Output 输出一个整数表示dd带回来的特产重量 Sample Input 2 3 6 1 3Sample …

vijos p1002——过河(noip2005提高组T2)

描述 在河上有一座独木桥&#xff0c;一只青蛙想沿着独木桥从河的一侧跳到另一侧。在桥上有一些石子&#xff0c;青蛙很讨厌踩在这些石子上。由于桥的长度和青蛙一次跳过的距离都是正整数&#xff0c;我们可以把独木桥上青蛙可能到达的点看成数轴上的一串整点&#xff1a;0&…