我有一个自定义用户模型,其中主键是email
字段,这也是USERNAME_FIELD
和REQUIRED_FIELD
。我的用户模型是这样的:
class User(AbstractBaseUser, PermissionsMixin):
'''
This is the username field which I've removed ...
username = models.CharField(
_('username'),
max_length=30,
primary_key=True,
help_text=_('Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[
RegexValidator(
r'^[\w.ñ@+-]+$',
_('Enter a valid username. This value may contain only '
'letters, numbers ' 'and @/./+/-/_ characters.')
),
],
error_messages={
'unique': _("A user with that username already exists."),
},
)
'''
email = models.EmailField(max_length=254, primary_key=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['email']
objects = UserManager()
UserManager
类是:
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
就像我最近删除了username
字段一样,当我执行makemigrations
进程时,我收到此错误:
File "/home/bgarcial/workspace/fuupbol_project/userprofiles/forms.py", line 26, in <module>
class CustomUserCreationForm(UserCreationForm):
File "/home/bgarcial/.virtualenvs/fuupbol2/lib/python3.5/site-packages/django/forms/models.py", line 257, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (username) specified for User
在我的forms.py中发生的事情是我使用UserCreationForm
类继承她,在我的CustomUserCreationForm
类
class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model =用户
在我的admin.py
class CustomUserAdmin(UserAdmin,):
form = CustomUserChangeForm
# Here I call the CustomUserCreationForm which inherit from
# UserCreationForm
add_form = CustomUserCreationForm
fieldsets = UserAdmin.fieldsets + (
(
None, {
'fields':(
... some fields ...
)
}
),
)
在这个admin.py文件中,我调用继承自的CustomUserCreationForm
UserCreationForm
django预先构建的课程
当我转到UserCreationForm
class Meta
source files时,username
属性中的fields
字段和{{{ 1}}属性
出于这个原因,field_classes
字段在我的自定义用户模型架构中是否持久存在,真的吗?
如何在不考虑此详细信息的情况下删除用户名,或按照username
课程及其含义进行操作...?
有一个更好的替代方法可以完成删除UserCreateForm
模型中的username
字段吗?