在Django中设置UserCreationForm的正确方法是什么?

6l7fqoea  于 2023-01-18  发布在  Go
关注(0)|答案(1)|浏览(173)

我有一个应用程序,它使用名为MyUser的自定义用户模型、自定义用户管理器和自定义UserCreationForm。我尝试将MyUser模型中的其余字段添加到UserCreationForm,但我一直收到错误:django.core.exceptions.FieldError: Unknown field(s) (username) specified for MyUser .设置自定义UserCreationForm的正确方法是什么?下面是我的代码。
Models.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()

Forms.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
...
2nbm6dog

2nbm6dog1#

我今天也遇到了同样的问题,这就是我解决它的方法。当我创建我的自定义用户模型时,我也创建了一个自定义UserCreation表单。所以当创建表单时,请确保使用您创建的自定义表单,而不是django提供的内置UserCreation表单。示例
这是我创建的自定义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

此外,如果您使用电子邮件登录,而不是用户名,并不希望有用户名字段,您可以删除它设置username=None在您的自定义用户模型,我希望这有助于。

相关问题