[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.pswp.cn/news/256055.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/256055.shtml
英文地址,請注明出處:http://en.pswp.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&…