【问题标题】:What is the proper way to set a UserCreationForm in Django?如何修复“django.core.exceptions.FieldError: Unknown field(s) (username) specified\”
【发布时间】: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
...

【问题讨论】:

  • 你让我们猜测错误发生在哪里。请更新问题以包含完整的错误回溯消息。

标签: python django


【解决方案1】:

我今天遇到了同样的问题,这就是我解决它的方法。当我创建我的自定义用户模型时,我还创建了一个自定义 UserCreation 表单。因此,在创建表单时,请确保使用您创建的自定义表单,而不是 django 提供的内置 UserCreation 表单。例子

这是我创建的自定义用户创建表单

class CustomUserCreationForm(UserCreationForm): # This is the form that will be used to create a new user

class Meta:
    model = CustomUser
    fields = ('email',) # This is the fields that will be displayed in the form

然后这就是我使用它的方式

class CandidateSignUpForm(CustomUserCreationForm):
# code here
)

class Meta(CustomUserCreationForm.Meta):
    model = CustomUser

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 2019-11-02
    • 2016-12-10
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多