django擴展用戶繼承AbstractUser


因為django自帶的用戶認證系統是通過username、password, 已經無法滿足現在大多數使用手機號和密碼驗證的需求,
所以:
A 需要自定義一個User包含手機號
B 需要自定義,通過手機號創建用戶的方法
C 修改authenticate通過手機號進行認證

 

 

1、在app01/models.py里面創建自定義User

from django.db import models
from django.contrib.auth.models import  AbstractUser

class User(AbstractUser):
    telephone = models.CharField(max_length=11, unique=True)
    school = models.CharField(max_length=100)

    USERNAME_FIELD = "telephone"   #USERNAME_FIELD作用,是執行authenticate驗證, username參數傳入后,實際校驗的是telephone字段

在settings.py里面,告訴django不再使用默認的User,使用自定義的User

AUTH_USER_MODEL = 'app01.User'

執行makemigrations和migrate

manage.py@untitled1019 > makemigrations
"D:\Program Files\PyCharm 2018.1.4\bin\runnerw.exe" "D:\Program Files\python3.6.7\python.exe" "D:\Program Files\PyCharm 2018.1.4\helpers\pycharm\django_manage.py" makemigrations D:/pythonWorkspace/untitled1019
Tracking file by folder pattern:  migrations
Migrations for 'app01':
  app01\migrations\0001_initial.py
manage.py@untitled1019 > migrate
"D:\Program Files\PyCharm 2018.1.4\bin\runnerw.exe" "D:\Program Files\python3.6.7\python.exe" "D:\Program Files\PyCharm 2018.1.4\helpers\pycharm\django_manage.py" migrate D:/pythonWorkspace/untitled1019
Tracking file by folder pattern:  migrations
Operations to perform:
  Apply all migrations: admin, app01, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying app01.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying sessions.0001_initial... OK

Process finished with exit code 0

同步完數據庫,可以看見 app01_user表里多了兩個字段, telephone、school

 

 

 

2、在app01/models.py里面自定義創建普通用戶和超級用戶的方法

from django.db import models
from django.contrib.auth.models import  AbstractUser, BaseUserManager

class UserManager(BaseUserManager):
    def _create_user(self , telephone, username, password, **kwargs):
        if not telephone:
            raise  ValueError("必須要傳遞手機號碼!")
        if not password:
            raise  ValueError("必須要傳遞密碼")
        user = self.model( telephone = telephone, username= username , **kwargs)
        user.set_password( password )
        user.save()
        return  user

    def create_user(self,  telephone, username, password, **kwargs):
        kwargs['is_superuser'] = False
        return self._create_user( telephone = telephone, username=username, password = password, **kwargs )

    def create_superuser(self, telephone, username, password, **kwargs):
        kwargs['is_superuser'] = True
        return  self._create_user( telephone = telephone, username=username, password = password, **kwargs )

class User(AbstractUser):
    telephone = models.CharField(max_length=11, unique=True)
    school = models.CharField(max_length=100)

    USERNAME_FIELD = "telephone"   #USERNAME_FIELD作用,是執行authenticate驗證, username參數傳入后,實際校驗的是telephone字段

    objects = UserManager()

 

3、在app01/views.py視圖中,調用創建用戶和驗證用戶的方法

from django.shortcuts import render, HttpResponse
from django.db import  connection
from app01.models import User
from django.contrib.auth import  authenticate


def test(request):
    #創建普通用戶
    # telephone = "17777677777"
    # password = "444444"
    # username = "zhiliao4"
    # user = User.objects.create_user( telephone=telephone, password=password, username=username)
    # print(user.username)

    #創建超級用戶
    # telephone = "19999699999"
    # password = "555555"
    # username = "zhiliao5"
    # user = User.objects.create_superuser(telephone=telephone, password=password, username=username)
    # print(user.username)

    #用戶認證
    user = authenticate(request, username="19999699999", password="555555")
    if user:
        print("驗證成功")
        print(user.username)
    else:
        print("驗證失敗")
    return HttpResponse("繼承AbstractUser擴展用戶")

創建用戶的執行結果如下:

 

 

 驗證用戶的執行結果如下:

System check identified no issues (0 silenced).
November 06, 2019 - 11:26:46
Django version 2.2.2, using settings 'untitled1019.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CTRL-BREAK.
驗證成功
[06/Nov/2019 11:26:50] "GET /test/ HTTP/1.1" 200 30
zhiliao5

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM