最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django如何繼承AbstractUser擴展字段

 更新時間:2020年11月27日 10:32:50   作者:-零  
這篇文章主要介紹了Django如何繼承AbstractUser擴展字段,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

使用django實現(xiàn)注冊登錄的話,注冊登錄都有現(xiàn)成的代碼,主要是自帶的User字段只有(email,username,password),所以需要擴展User,來增加自己需要的字段

AbstractUser擴展模型User:如果模型User內置的方法符合開發(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內置的兼容python2和python3的unicode語法的一個裝飾器
只是針對 __str__ 方法而用的,__str__方法是為了后臺管理(admin)和django shell的顯示,Meta類也是為后臺顯示服務的
"""
class MyUser(AbstractUser):
  qq = models.CharField(u'qq號', max_length=16)
  weChat =models.CharField(u'微信賬號', max_length=100)
  mobile =models.CharField(u'手機號', primary_key=True, max_length=11)
  identicard =models.BooleanField(u'×××認證', default=False)               #默認是0,未認證, 1:×××認證, 2:視頻認證
  refuserid = models.CharField(u'推薦人ID', max_length=20)
  Level = models.CharField(u'用戶等級', default='0', max_length=2)            #默認是0,用戶等級0-9
  vevideo = models.BooleanField(u'視頻認證', default=False)           #默認是0,未認證。 1:已認證
  Type =models.CharField(u'用戶類型', default='0', max_length=1)             #默認是0,未認證, 1:刷手 2:商家
 
  def __str__(self):
    return self.username

settings.py

AUTH_USER_MODEL = 'appname.MyUser'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)

注意:

1、擴展user表后,要在settings.py 添加

AUTH_USER_MODEL = 'appname.擴展user的class name'

2、認證后臺要在settings添加,尤其記得加逗號,否則報錯

認證后臺不加的報錯

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='確認密碼',widget=forms.PasswordInput())
  mobile = forms.CharField(label='手機號', 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、登陸的時候用自帶的認證模塊總是報none

user = authenticate(username=username, password=password)
print(user)

查看源碼發(fā)現(xiàn)是check_password的方法是用hash進行校驗,之前注冊的password寫法是

user.password=password

這種寫法是明文入庫,需要更改密碼的入庫寫法

user.set_password(password)

補充

一個快速拿到User表的方法,特別在擴展User表時,你在settings.py配置的User。

from django.contrib.auth import get_user_model
User = get_user_model()

別在其他視圖或者模型里導入你擴展的MyUser model。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • Python中defaultdict與dict的差異詳情

    Python中defaultdict與dict的差異詳情

    這篇文章主要介紹了Python中defaultdict與dict的差異,在collections模塊中的defauldict使用時與dict有何不同,為何我們用dict中的key值不存在時會報錯,而defaudict不會報錯,下面文章做出解答,需要的朋友可以參考一下
    2021-11-11
  • 讓python同時兼容python2和python3的8個技巧分享

    讓python同時兼容python2和python3的8個技巧分享

    這篇文章主要介紹了讓python同時兼容python2和python3的8個技巧分享,對代碼稍微做些修改就可以很好的同時支持python2和python3的,需要的朋友可以參考下
    2014-07-07
  • Python在字符串中處理html和xml的方法

    Python在字符串中處理html和xml的方法

    這篇文章主要介紹了Python在字符串中處理html和xml的方法,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-07-07
  • Python文件操作基礎及異常處理

    Python文件操作基礎及異常處理

    這篇文章主要介紹了文件操作的基本方法,包括如何打開和關閉文件、使用with語句管理文件、讀取和寫入文件內容、處理文件異常、進行二進制文件操作以及文件路徑的說明,,需要的朋友可以參考下
    2025-03-03
  • pytorch  RNN參數(shù)詳解(最新)

    pytorch  RNN參數(shù)詳解(最新)

    這篇文章主要介紹了pytorch  RNN參數(shù)詳解,這個示例代碼展示了如何使用 PyTorch 定義和訓練一個 LSTM 模型,并詳細解釋了每個類和方法的參數(shù)及其作用,需要的朋友可以參考下
    2024-06-06
  • Python使用Streamlit快速構建一個數(shù)據(jù)應用程序

    Python使用Streamlit快速構建一個數(shù)據(jù)應用程序

    Streamlit是一個開源的Python庫,它允許數(shù)據(jù)科學家和開發(fā)人員快速創(chuàng)建和分享數(shù)據(jù)應用程序,而無需具備復雜的Web開發(fā)經(jīng)驗,本文將介紹Streamlit的基本用法,并通過一個實際案例展示如何快速構建一個簡單的數(shù)據(jù)應用程序,需要的朋友可以參考下
    2025-03-03
  • python實現(xiàn)橫向拼接圖片

    python實現(xiàn)橫向拼接圖片

    這篇文章主要為大家詳細介紹了python實現(xiàn)橫向拼接圖片,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-03-03
  • 淺析對torch.unsqueeze()函數(shù)理解

    淺析對torch.unsqueeze()函數(shù)理解

    torch.unsqueeze()函數(shù)起到升維的作用,dim等于幾表示在第幾維度加一,這篇文章主要介紹了對torch.unsqueeze()函數(shù)理解深度解析,感興趣的朋友跟隨小編一起看看吧
    2024-06-06
  • python使用htmllib分析網(wǎng)頁內容的方法

    python使用htmllib分析網(wǎng)頁內容的方法

    這篇文章主要介紹了python使用htmllib分析網(wǎng)頁內容的方法,涉及Python使用htmllib模塊的相關技巧,需要的朋友可以參考下
    2015-05-05
  • python中enumerate的用法實例解析

    python中enumerate的用法實例解析

    這篇文章主要介紹了python中enumerate的用法,對Python初學者而言是非常重要的概念,需要的朋友可以參考下
    2014-08-08

最新評論

东城区| 鹤峰县| 太仆寺旗| 宁明县| 开原市| 绥中县| 锦州市| 河西区| 峨边| 班戈县| 西乡县| 永福县| 鹤庆县| 武宣县| 古田县| 军事| 定结县| 桂林市| 县级市| 丰城市| 三江| 宜宾县| 无锡市| 凤翔县| 资溪县| 清原| 庆城县| 美姑县| 长春市| 安塞县| 长兴县| 平塘县| 固安县| 茶陵县| 涡阳县| 古蔺县| 屏东市| 宜良县| 香河县| 潜山县| 清丰县|