django用戶注冊、登錄、注銷和用戶擴(kuò)展的示例
用戶部分是一個網(wǎng)站的基本功能,django對這部分進(jìn)行了很好的封裝,我們只需要在django的基礎(chǔ)上做些簡單的修改就可以達(dá)到我們想要的效果
首先我假設(shè)你對django的session、cookie和數(shù)據(jù)庫、admin部分都有一定的了解,不了解的可以參考這個教程:http://djangobook.py3k.cn/2.0/
1、用戶登錄:
首先假設(shè)有這樣的登錄界面:
處理登錄的視圖代碼如下:
def userLogin(request): curtime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()); if request.method=='POST': print("POST") username=request.POST.get('name','') password=request.POST.get('password','') user= auth.authenticate(username=username,password=password)#a*********** if user and user.is_active: auth.login(request, user)#b************ return HttpResponseRedirect("/user") return render_to_response("blog/userlogin.html",RequestContext(request,{'curtime':curtime}))
注:a、這里是用django自己的auth框架驗證用戶名和密碼,有人會說,這樣太不靈活了,我想用郵箱登錄呢?后面我們會說直接用django.contrib.auth.models.User 模型來直接操作用戶數(shù)據(jù),這樣就可以做自己想要的驗證了。
b、用戶信息被驗證無誤后需要把用戶登錄的信息寫入session中
2、用戶注銷
注銷比較簡單,只需要在session中刪除對應(yīng)的user信息就ok了
def userLogout(request): auth.logout(request) return HttpResponseRedirect('/user')
3、用戶注冊
注冊的界面如下:
用戶名、密碼、郵箱是基本的注冊信息,這是django自帶的,下面的電話是擴(kuò)展的用戶信息,至于這么擴(kuò)展用戶信息,一會會講,先透露下我采用的是profile的擴(kuò)展方式(個人喜好吧,我覺得這種方式簡單明了)
注冊的視圖view代碼:
def userRegister(request): curtime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()); if request.user.is_authenticated():#a******************* return HttpResponseRedirect("/user") try: if request.method=='POST': username=request.POST.get('name','') password1=request.POST.get('password1','') password2=request.POST.get('password2','') email=request.POST.get('email','') phone=request.POST.get('phone','') errors=[] registerForm=RegisterForm({'username':username,'password1':password1,'password2':password2,'email':email})#b******** if not registerForm.is_valid(): errors.extend(registerForm.errors.values()) return render_to_response("blog/userregister.html",RequestContext(request,{'curtime':curtime,'username':username,'email':email,'errors':errors})) if password1!=password2: errors.append("兩次輸入的密碼不一致!") return render_to_response("blog/userregister.html",RequestContext(request,{'curtime':curtime,'username':username,'email':email,'errors':errors})) filterResult=User.objects.filter(username=username)#c************ if len(filterResult)>0: errors.append("用戶名已存在") return render_to_response("blog/userregister.html",RequestContext(request,{'curtime':curtime,'username':username,'email':email,'errors':errors})) user=User()#d************************ user.username=username user.set_password(password1) user.email=email user.save() #用戶擴(kuò)展信息 profile profile=UserProfile()#e************************* profile.user_id=user.id profile.phone=phone profile.save() #登錄前需要先驗證 newUser=auth.authenticate(username=username,password=password1)#f*************** if newUser is not None: auth.login(request, newUser)#g******************* return HttpResponseRedirect("/user") except Exception,e: errors.append(str(e)) return render_to_response("blog/userregister.html",RequestContext(request,{'curtime':curtime,'username':username,'email':email,'errors':errors})) return render_to_response("blog/userregister.html",RequestContext(request,{'curtime':curtime}))
注:
a、驗證用戶是否登錄了,已經(jīng)登錄就沒必要注冊了(當(dāng)然這只是練習(xí)使用,實際生產(chǎn)情況可能不一樣)
b、注冊表單傳過來的數(shù)據(jù)需要一些基本的驗證,怎么驗證表單數(shù)據(jù)可以參考這個教程:http://djangobook.py3k.cn/2.0/chapter07/
c、用User模型查找要注冊的用戶名是否存在,如果用戶已經(jīng)存在就需要提示注冊的客戶更換用戶名
d、直接利用User模型把通過驗證的用戶數(shù)據(jù)存入數(shù)據(jù)庫,需要注意的是,保存密碼信息時需要使用set_password方法(因為這里有個加密的過程)
e、存儲用戶的擴(kuò)展信息(這里是用戶的電話號碼),這里用到自定義的用戶擴(kuò)展模型UserProfile,具體怎么擴(kuò)展用戶后面會講
f、用戶登錄前需要先進(jìn)行驗證,要不然會出錯
g、用戶登錄
4、用戶擴(kuò)展
網(wǎng)上關(guān)于django的用戶擴(kuò)展方式有好幾種,個人比較傾向于Profile的方式,主要是這種方式簡單清楚,擴(kuò)展步驟如下:
A、在你App的models中新建一個UserProfile模型
from django.contrib.auth.models import User class UserProfile(models.Model): user=models.OneToOneField(User,unique=True,verbose_name=('用戶'))#a****** phone=models.CharField(max_length=20)#b******
注:a、UserProfile其實就是一個普通的model,然后通過這一句與django的User模型建立聯(lián)系
b、擴(kuò)展的用戶信息
B、python manage.py syncdb 在數(shù)據(jù)庫內(nèi)創(chuàng)建userprofile的表
C、如何調(diào)用user的擴(kuò)展信息呢?很簡單,先得到user,然后通過user提供的get_profile()來得到profile對象,比如
user.get_profile().phone
D、如何更新和存儲user的profile信息呢,其實在之前的用戶注冊部分我們已經(jīng)使用了這樣的功能,userprofile其實也是一個model,我們只要通過user模型得到user的id,就可以通過UserProfile模型來操作對應(yīng)的profile信息:
user=User() user.username=username user.set_password(password1) user.email=email user.save() #用戶擴(kuò)展信息 profile profile=UserProfile() profile.user_id=user.id profile.phone=phone profile.save()
E、我們能在程序中操作用戶擴(kuò)展信息了,那我想在admin后臺中編輯擴(kuò)展信息要怎么做呢:
很簡單,只要在你的APP的admin.py中添加下面的語句就行了
class UserProfileInline(admin.StackedInline): model=UserProfile fk_name='user' max_num=1 class UserProfileAdmin(UserAdmin): inlines = [UserProfileInline, ] admin.site.unregister(User) admin.site.register(User,UserProfileAdmin)
這是我學(xué)習(xí)django時的一些經(jīng)驗,也許不全對,僅供參考,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Django小白教程之Django用戶注冊與登錄
- django的登錄注冊系統(tǒng)的示例代碼
- Django實現(xiàn)auth模塊下的登錄注冊與注銷功能
- django 框架實現(xiàn)的用戶注冊、登錄、退出功能示例
- Django調(diào)用百度AI接口實現(xiàn)人臉注冊登錄代碼實例
- Django用戶登錄與注冊系統(tǒng)的實現(xiàn)示例
- django+vue實現(xiàn)注冊登錄的示例代碼
- Django 登錄注冊的實現(xiàn)示例
- Django制作簡易注冊登錄系統(tǒng)的實現(xiàn)示例
- django authentication 登錄注冊的實現(xiàn)示例
相關(guān)文章
詳解Python調(diào)用華為API實現(xiàn)圖像標(biāo)簽
華為云圖像標(biāo)簽可識別上千種通用物體以及數(shù)百種場景標(biāo)簽,一個圖像可包含多個標(biāo)簽內(nèi)容,語義內(nèi)容非常豐富。本文將通過Python調(diào)用華為API實現(xiàn)圖像標(biāo)簽,需要的可以參考一下2022-04-04Python打包文件執(zhí)行報錯:ModuleNotFoundError: No module 
這篇文章給大家介紹了Python打包文件執(zhí)行報錯:ModuleNotFoundError: No module named ‘pymssql‘的解決方法,如果有遇到相同問題的朋友可以參考閱讀一下本文2023-10-10以視頻爬取實例講解Python爬蟲神器Beautiful Soup用法
這篇文章主要以視頻爬取實例來講解Python爬蟲神器Beautiful Soup的用法,Beautiful Soup是一個為Python獲取數(shù)據(jù)而設(shè)計的包,簡潔而強(qiáng)大,需要的朋友可以參考下2016-01-01