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

 

 

 

posted on 2019-11-06 10:39  芦苇草鱼  阅读(738)  评论(0编辑  收藏  举报