亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Django如何繼承AbstractUser擴(kuò)展字段

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

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

AbstractUser擴(kuò)展模型User:如果模型User內(nèi)置的方法符合開發(fā)需求,在不改變這些函數(shù)方法的情況下,添加模型User的額外字段,可通過AbstractUser方式實(shí)現(xiàn)。使用AbstractUser定義的模型會(huì)替換原有模型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語法的一個(gè)裝飾器
只是針對(duì) __str__ 方法而用的,__str__方法是為了后臺(tái)管理(admin)和django shell的顯示,Meta類也是為后臺(tái)顯示服務(wù)的
"""
class MyUser(AbstractUser):
  qq = models.CharField(u'qq號(hào)', max_length=16)
  weChat =models.CharField(u'微信賬號(hào)', max_length=100)
  mobile =models.CharField(u'手機(jī)號(hào)', 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'用戶等級(jí)', default='0', max_length=2)            #默認(rèn)是0,用戶等級(jí)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)證后臺(tái)要在settings添加,尤其記得加逗號(hào),否則報(bào)錯(cuò)

認(rèn)證后臺(tái)不加的報(bào)錯(cuò)

Django-AttributeError 'User' object has no attribute 'backend'

沒加逗號(hào)的報(bào)錯(cuò)

ImportError: a doesn't look like a module path

form.py

#coding:utf-8
from django import forms
 
#注冊(cè)表單
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ī)號(hào)', max_length=11)
  email = forms.EmailField()
  qq = forms.CharField(label='QQ號(hào)', max_length=16)
  type = forms.ChoiceField(label='注冊(cè)類型', choices=(('buyer','買家'),('saler','商家')))
 
  def clean(self):
    if not self.is_valid():
      raise forms.ValidationError('所有項(xiàng)都為必填項(xiàng)')
    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
 
#注冊(cè)
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驗(yàn)證用戶名密碼
      if user is not None:                         #判斷用戶是否存在
        if user.is_active:                         #判斷用戶是否激活
          login(request,user)                         #用戶信息驗(yàn)證成功后把登陸信息寫入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、登陸的時(shí)候用自帶的認(rèn)證模塊總是報(bào)none

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

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

user.password=password

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

user.set_password(password)

補(bǔ)充

一個(gè)快速拿到User表的方法,特別在擴(kuò)展User表時(shí),你在settings.py配置的User。

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

別在其他視圖或者模型里導(dǎo)入你擴(kuò)展的MyUser model。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python中append函數(shù)用法講解

    python中append函數(shù)用法講解

    在本篇文章里小編給大家整理的是一篇關(guān)于python中append函數(shù)用法講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。
    2020-12-12
  • 實(shí)例解析Python設(shè)計(jì)模式編程之橋接模式的運(yùn)用

    實(shí)例解析Python設(shè)計(jì)模式編程之橋接模式的運(yùn)用

    這篇文章主要介紹了Python設(shè)計(jì)模式編程之橋接模式的運(yùn)用,橋接模式主張把抽象部分與它的實(shí)現(xiàn)部分分離,需要的朋友可以參考下
    2016-03-03
  • python中tqdm使用,對(duì)于for和while下的兩種不同情況問題

    python中tqdm使用,對(duì)于for和while下的兩種不同情況問題

    這篇文章主要介紹了python中tqdm使用,對(duì)于for和while下的兩種不同情況問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • 推薦Python小白理想的IDE編輯器thonny

    推薦Python小白理想的IDE編輯器thonny

    這篇文章主要為大家介紹了推薦一款Python編輯器thonny,非常適合Python使用,具體原因文中給出詳細(xì)說明,希望能夠有所幫助,祝大家多多進(jìn)步
    2021-10-10
  • python 實(shí)現(xiàn)在tkinter中動(dòng)態(tài)顯示label圖片的方法

    python 實(shí)現(xiàn)在tkinter中動(dòng)態(tài)顯示label圖片的方法

    今天小編就為大家分享一篇python 實(shí)現(xiàn)在tkinter中動(dòng)態(tài)顯示label圖片的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • Python使用python-docx讀寫word文檔

    Python使用python-docx讀寫word文檔

    這篇文章主要為大家詳細(xì)介紹了Python使用python-docx讀寫word文檔,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • selenium與xpath之獲取指定位置的元素的實(shí)現(xiàn)

    selenium與xpath之獲取指定位置的元素的實(shí)現(xiàn)

    這篇文章主要介紹了selenium與xpath之獲取指定位置的元素的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • python默認(rèn)參數(shù)調(diào)用方法解析

    python默認(rèn)參數(shù)調(diào)用方法解析

    這篇文章主要介紹了python默認(rèn)參數(shù)調(diào)用方法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • Python中無限循環(huán)需要什么條件

    Python中無限循環(huán)需要什么條件

    在本篇文章里小編給大家分享的是關(guān)于Python中無限循環(huán)的條件的相關(guān)文章,需要的朋友們可以參考下。
    2020-05-05
  • Python爬蟲之Scrapy環(huán)境搭建案例教程

    Python爬蟲之Scrapy環(huán)境搭建案例教程

    這篇文章主要介紹了Python爬蟲之Scrapy環(huán)境搭建案例教程,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-07-07

最新評(píng)論