【发布时间】: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