【发布时间】:2022-10-20 17:43:10
【问题描述】:
我有一个使用名为 MyUser 的自定义用户模型、自定义用户管理器和自定义 UserCreationForm 的应用程序。我正在尝试将 MyUser 模型中的其余字段添加到 UserCreationForm,但我不断收到错误消息:django.core.exceptions.FieldError: Unknown field(s) (username) specified for MyUser。设置自定义 UserCreationForm 的正确方法是什么?为什么我会收到此错误?这是我的代码。
模型.py
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
import uuid
class UserManager(BaseUserManager):
def create_user(self, fname, lname, email, phone, password=None):
if not email:
raise ValueError('You must enter an email address')
user = self.model(
fname=fname,
lname=lname,
email=self.normalize_email(email),
password=password,
is_superuser=False
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, password):
user=self.create_user(self, fname, lname, email, phone, password)
user.staff=True
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user=self.create_user(self, fname, lname, email, phone, password)
user.staff=True
user.admin=True
user.is_superuser=True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser, PermissionsMixin):
fname=models.CharField(max_length=100)
lname=models.CharField(max_length=100)
email=models.EmailField(max_length=200, unique=True)
phone=models.CharField(max_length=15)
password=models.CharField(max_length=200)
user_id=models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4)
is_active=models.BooleanField(default=True)
staff=models.BooleanField(default=False)
admin=models.BooleanField(default=False)
USERNAME_FIELD='email'
required_fields=['fname', 'lname', 'email', 'password']
@property
def is_staff(self):
#is the user staff?
return self.staff
@property
def is_admin(self):
#is the user an admin?
return self.admin
objects = UserManager()
表格.py
from django import forms
from django.forms import ModelForm
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth import get_user_model
MyUser = get_user_model()
class MyUserLogin(AuthenticationForm):
class Meta:
model=MyUser
fields=['email', 'password']
class MyUserSignup(UserCreationForm):
class Meta(UserCreationForm):
model=MyUser
fields=UserCreationForm.Meta.fields + ('fname', 'lname', 'phone')
def clean_email(self):
email=self.cleaned_data.get('email')
email_exists=MyUser.objects.filter(email__iexact=email).exists()
if email_exists:
raise self.add_error('There is already an account registered with that email.')
return email
...
【问题讨论】:
-
你让我们猜测错误发生在哪里。请更新问题以包含完整的错误回溯消息。