【问题标题】:How to use phone number as username for Django authentication如何使用电话号码作为 Django 身份验证的用户名
【发布时间】:2018-03-18 12:21:06
【问题描述】:

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

models.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 和迁移,一切都好!但后来我尝试创建超级用户,在添加字段(电话、电子邮件、密码)后发生错误:

NameError: name 'phone' is not defined

【问题讨论】:

  • 在您的_create_user 方法中,您为什么使用phone=self.phone?我认为这是触发错误:尝试删除该行
  • 我不明白为什么,但它有效
  • 是的,这就是我们这个世界的美妙之处,呵呵。我认为这是因为 UserManager 没有 phone 属性。 phone=self.phone 也不好,如果你收到一个参数(电话)是设置模型属性 self.phone=phone 不是相反。

标签: django


【解决方案1】:

您是否通过提及AUTH_USER_MODEL = 'myapp.MyUser'settings.py 中注册了您的自定义用户模型?除非这样做,否则您的模型将不会被视为用户模型。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 是的,我的注意力不集中。我修好了它。但是出现了新的错误phone = self.phone AttributeError: 'UserManager' object has no attribute 'phone'
    • 如果您已经将电话分配给自己,则只能使用 phone= self.phone。 (Self.phone = my_phone_number)。
    猜你喜欢
    • 1970-01-01
    • 2020-11-08
    • 2023-03-05
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多