gpt4 book ai didi

django - 如何使用电话号码作为 Django 身份验证的用户名

转载 作者:行者123 更新时间:2023-12-03 17:04:52 26 4
gpt4 key购买 nike

我正在尝试扩展用户模型并使用用户名电话号码。我正在为新用户模型创建自定义用户模型和自定义管理器。
模型.py

from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.core.validators import RegexValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _


class UserManager(BaseUserManager):
"""Define a model manager for User model with no username field."""

use_in_migrations = True

def _create_user(self, phone, password, **extra_fields):
"""Create and save a User with the given phone and password."""
if not phone:
raise ValueError('The given phone must be set')
self.phone = phone
user = self.model(phone=phone, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user

def create_user(self, phone, password=None, **extra_fields):
"""Create and save a regular User with the given phone and password."""
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(phone, password, **extra_fields)

def create_superuser(self, phone, password, **extra_fields):
"""Create and save a SuperUser with the given phone and password."""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)

if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')

return self._create_user(phone, password, **extra_fields)

class User(AbstractUser):
"""User model."""

username = None
email = models.EmailField(blank=True, null=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone = models.CharField(_('phone number'), validators=[phone_regex], max_length=17, unique=True) # validators should be a list
is_partner = models.BooleanField(default=False)
is_client = models.BooleanField(default=False)


USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = ['email']

objects = UserManager()
我已经完成了 makemigrations 和 migrate,一切都好!但是后来我尝试创建 super 用户,在添加字段(电话、电子邮件、密码)后出现错误:
NameError: name 'phone' is not defined

最佳答案

您将电子邮件和密码传递给 create_superuser(),也许您想通过电话代替?

关于django - 如何使用电话号码作为 Django 身份验证的用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49347814/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com