Django如何繼承AbstractUser擴(kuò)展字段
使用django實現(xiàn)注冊登錄的話,注冊登錄都有現(xiàn)成的代碼,主要是自帶的User字段只有(email,username,password),所以需要擴(kuò)展User,來增加自己需要的字段
AbstractUser擴(kuò)展模型User:如果模型User內(nèi)置的方法符合開發(fā)需求,在不改變這些函數(shù)方法的情況下,添加模型User的額外字段,可通過AbstractUser方式實現(xiàn)。使用AbstractUser定義的模型會替換原有模型User。
代碼如下:
model.py
#coding:utf8
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import python_2_unicode_compatible
# Create your models here.
@python_2_unicode_compatible
"""是django內(nèi)置的兼容python2和python3的unicode語法的一個裝飾器
只是針對 __str__ 方法而用的,__str__方法是為了后臺管理(admin)和django shell的顯示,Meta類也是為后臺顯示服務(wù)的
"""
class MyUser(AbstractUser):
qq = models.CharField(u'qq號', max_length=16)
weChat =models.CharField(u'微信賬號', max_length=100)
mobile =models.CharField(u'手機(jī)號', primary_key=True, max_length=11)
identicard =models.BooleanField(u'×××認(rèn)證', default=False) #默認(rèn)是0,未認(rèn)證, 1:×××認(rèn)證, 2:視頻認(rèn)證
refuserid = models.CharField(u'推薦人ID', max_length=20)
Level = models.CharField(u'用戶等級', default='0', max_length=2) #默認(rèn)是0,用戶等級0-9
vevideo = models.BooleanField(u'視頻認(rèn)證', default=False) #默認(rèn)是0,未認(rèn)證。 1:已認(rèn)證
Type =models.CharField(u'用戶類型', default='0', max_length=1) #默認(rèn)是0,未認(rèn)證, 1:刷手 2:商家
def __str__(self):
return self.username
settings.py
AUTH_USER_MODEL = 'appname.MyUser'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
注意:
1、擴(kuò)展user表后,要在settings.py 添加
AUTH_USER_MODEL = 'appname.擴(kuò)展user的class name'
2、認(rèn)證后臺要在settings添加,尤其記得加逗號,否則報錯
認(rèn)證后臺不加的報錯
Django-AttributeError 'User' object has no attribute 'backend'
沒加逗號的報錯
ImportError: a doesn't look like a module path
form.py
#coding:utf-8
from django import forms
#注冊表單
class RegisterForm(forms.Form):
username = forms.CharField(label='用戶名',max_length=100)
password = forms.CharField(label='密碼',widget=forms.PasswordInput())
password2 = forms.CharField(label='確認(rèn)密碼',widget=forms.PasswordInput())
mobile = forms.CharField(label='手機(jī)號', max_length=11)
email = forms.EmailField()
qq = forms.CharField(label='QQ號', max_length=16)
type = forms.ChoiceField(label='注冊類型', choices=(('buyer','買家'),('saler','商家')))
def clean(self):
if not self.is_valid():
raise forms.ValidationError('所有項都為必填項')
elif self.cleaned_data['password2'] != self.cleaned_data['password']:
raise forms.ValidationError('兩次輸入密碼不一致')
else:
cleaned_data = super(RegisterForm, self).clean()
return cleaned_data
#登陸表單
class LoginForm(forms.Form):
username = forms.CharField(label='用戶名',widget=forms.TextInput(attrs={"placeholder": "用戶名", "required": "required",}),
max_length=50, error_messages={"required": "username不能為空",})
password = forms.CharField(label='密碼',widget=forms.PasswordInput(attrs={"placeholder": "密碼", "required": "required",}),
max_length=20, error_messages={"required": "password不能為空",})
遷移數(shù)據(jù)庫
python manage.py makemigrations
python manage.py migrate
views.py
from django.shortcuts import render,render_to_response
from .models import MyUser
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
import time
from .myclass import form
from django.template import RequestContext
from django.contrib.auth import authenticate,login,logout
#注冊
def register(request):
error = []
# if request.method == 'GET':
# return render_to_response('register.html',{'uf':uf})
if request.method == 'POST':
uf = form.RegisterForm(request.POST)
if uf.is_valid():
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
password2 = uf.cleaned_data['password2']
qq = uf.cleaned_data['qq']
email = uf.cleaned_data['email']
mobile = uf.cleaned_data['mobile']
type = uf.cleaned_data['type']
if not MyUser.objects.all().filter(username=username):
user = MyUser()
user.username = username
user.set_password(password)
user.qq = qq
user.email = email
user.mobile = mobile
user.type = type
user.save()
return render_to_response('member.html', {'username': username})
else:
uf = form.RegisterForm()
return render_to_response('register.html',{'uf':uf,'error':error})
#登陸
def do_login(request):
if request.method =='POST':
lf = form.LoginForm(request.POST)
if lf.is_valid():
username = lf.cleaned_data['username']
password = lf.cleaned_data['password']
user = authenticate(username=username, password=password) #django自帶auth驗證用戶名密碼
if user is not None: #判斷用戶是否存在
if user.is_active: #判斷用戶是否激活
login(request,user) #用戶信息驗證成功后把登陸信息寫入session
return render_to_response("member.html", {'username':username})
else:
return render_to_response('disable.html',{'username':username})
else:
return HttpResponse("無效的用戶名或者密碼!!!")
else:
lf = form.LoginForm()
return render_to_response('index.html',{'lf':lf})
#退出
def do_logout(request):
logout(request)
return HttpResponseRedirect('/')
注意:
1、登陸的時候用自帶的認(rèn)證模塊總是報none
user = authenticate(username=username, password=password)
print(user)
查看源碼發(fā)現(xiàn)是check_password的方法是用hash進(jìn)行校驗,之前注冊的password寫法是
user.password=password
這種寫法是明文入庫,需要更改密碼的入庫寫法
user.set_password(password)
補(bǔ)充
一個快速拿到User表的方法,特別在擴(kuò)展User表時,你在settings.py配置的User。
from django.contrib.auth import get_user_model
User = get_user_model()
別在其他視圖或者模型里導(dǎo)入你擴(kuò)展的MyUser model。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Django User 模塊之 AbstractUser 擴(kuò)展詳解
- JavaSE static final及abstract修飾符實例解析
- PHP中abstract(抽象)、final(最終)和static(靜態(tài))原理與用法詳解
- Python2和Python3中@abstractmethod使用方法
- JAVA抽象類和抽象方法(abstract)實例分析
- Springboot源碼 AbstractAdvisorAutoProxyCreator解析
- java編程abstract類和方法詳解
- 淺談利用Spring的AbstractRoutingDataSource解決多數(shù)據(jù)源的問題
相關(guān)文章
實例解析Python設(shè)計模式編程之橋接模式的運(yùn)用
這篇文章主要介紹了Python設(shè)計模式編程之橋接模式的運(yùn)用,橋接模式主張把抽象部分與它的實現(xiàn)部分分離,需要的朋友可以參考下2016-03-03
python中tqdm使用,對于for和while下的兩種不同情況問題
這篇文章主要介紹了python中tqdm使用,對于for和while下的兩種不同情況問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
python 實現(xiàn)在tkinter中動態(tài)顯示label圖片的方法
今天小編就為大家分享一篇python 實現(xiàn)在tkinter中動態(tài)顯示label圖片的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
selenium與xpath之獲取指定位置的元素的實現(xiàn)
這篇文章主要介紹了selenium與xpath之獲取指定位置的元素的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
python默認(rèn)參數(shù)調(diào)用方法解析
這篇文章主要介紹了python默認(rèn)參數(shù)調(diào)用方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-02-02

