Django自定义用户模型:用户创建问题

时间:2018-12-24 09:44:22

标签: python django

我已经创建了一个自定义用户模型,用电子邮件替换用户名。但是,当我尝试从Django Admin添加用户时,出现错误:

 Please correct the errors below. 

该错误消息没有其他信息。

自定义用户的代码:

class User(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(
        verbose_name="email_address",
        max_length=255,
        unique=True,
    )
    name = models.CharField(max_length=255)

    is_staff = models.BooleanField(
        default=False,
    )
    is_active = models.BooleanField(
        default=True,
    )

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def get_full_name(self):
        return self.name

    def __str__(self):
        return self.email

自定义用户管理器代码:

class UserManager(BaseUserManager):

    def _create_user(self, email, password, **kwargs):
        if not email:
            raise ValueError("Email is required")

        email = self.normalize_email(email)
        user = self.model(email=email, **kwargs)
        user.set_password(password)
        user.save()
        return user

    def create_user(self, email, password=None, **extra_fields):
        """Create and save a regular User with the given email and     password."""
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **kwargs):
        kwargs.setdefault('is_staff', True)
        kwargs.setdefault('is_superuser', True)
        kwargs.setdefault('is_active', True)

        if kwargs.get('is_staff') is not True:
            raise ValueError("Superuser must have is_staff True")
        if kwargs.get('is_superuser') is not True:
            raise ValueError("Superuser must have is_superuser True")
        return self._create_user(email, password, **kwargs)

及其管理员代码:

class CustomUserAdmin(BaseUserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserCreationForm

    list_display = ('id', 'email', 'is_superuser')
    list_filter = ('is_superuser',)

    fieldsets = (
        (None, {'fields': ('name', 'email', 'password')}),
        ('Permissions', {'fields': ('is_superuser', 'is_staff')}),
    )
    add_fieldsets = fieldsets

    search_fields = ('name', 'email')
    ordering = ('name', 'email')

    filter_horizontal = ()

自定义用户表单:

# users/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import User

class CustomUserCreationForm(UserCreationForm):

    class Meta:
        model = User
        fields = ('name', 'email')

class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = User
        fields = ('name', 'email')

我尝试了许多更改,但无法找出问题所在。在此方面,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

更改:

class Meta: model = User fields = ('name', 'email')

收件人:

class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields + ('name', 'email')