Django 错误 admin.E033:用户名不是 users.CustomUser 的属性。为什么我的自定义用户管理员不起作用?

the*_*ser 9 python django

我正在 Django 中创建自定义用户模型。我已经定义了一个自定义用户模型 (users.CustomUser),它是 AbstractBaseUser 的子类。我创建了一个自定义用户管理器 (users.CustomUserManager),它是 BaseUserManager 的子类并且可以正常工作。我还创建了一个自定义用户管理员,它是 UserAdmin 的子类,因为我的 CustomUser 模型没有用户名字段(它使用“电子邮件”代替)。

据我所知,我已经正确编码了所有内容,但是当我运行“python manage.py makemigrations”时,我收到一条错误消息:

<class 'users.admin.CustomUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'users.CustomUser'.
Run Code Online (Sandbox Code Playgroud)

我被困在这里。

我已经尝试了以下操作:(1)在我的自定义用户模型类中将用户名字段定义为电子邮件(2)尝试在我的自定义用户模型类和自定义用户管理员中将用户名设置为无(3)创建自定义用户注册和更改表单并将它们注册到我的自定义用户管理员

<class 'users.admin.CustomUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'users.CustomUser'.
Run Code Online (Sandbox Code Playgroud)
# models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from phonenumber_field.modelfields import PhoneNumberField
from .managers import CustomUserManager

class CustomUser(AbstractBaseUser, PermissionsMixin):
    username = None
    firstname = models.CharField(max_length = 60)
    lastname = models.CharField(max_length = 60)
    email = models.EmailField(max_length = 240, unique=True)
    phone = PhoneNumberField(null=True, blank=True)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True)
    password = models.CharField(max_length = 240)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['firstname', 'lastname', 'company', 'password']

    objects = CustomUserManager()

    def __str__(self):
        return self.email
Run Code Online (Sandbox Code Playgroud)
# managers.py
from django.contrib.auth.base_user import BaseUserManager

class CustomUserManager(BaseUserManager):
    def create_user(self, email, firstname, lastname, company, password, **extra_fields):
        email = self.normalize_email(email)
        user = self.model(
            email=email,
            firstname=firstname,
            lastname=lastname,
            company=company,
            **extra_fields
        )
        user.set_password(password)
        user.save()
        return user
Run Code Online (Sandbox Code Playgroud)
#forms.py
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser, Company
from phonenumber_field.modelfields import PhoneNumberField
from django.core.exceptions import ValidationError

class CustomUserRegistrationForm(forms.ModelForm):
    firstname = forms.CharField(label = 'First Name*', max_length = 120)
    lastname = forms.CharField(label = 'Last Name*', max_length = 120)
    email = forms.EmailField(label = 'Email*')
    phone = PhoneNumberField()
    company = forms.ModelChoiceField(queryset = Company.objects.all(), label = 'Company*', required = True)
    password = forms.CharField(label = 'Password*', min_length = 5, max_length = 50, widget = forms.PasswordInput)
    password2 = forms.CharField(label = 'Confirm Password*', min_length = 5, max_length = 50, widget = forms.PasswordInput)

    class Meta:
        model = CustomUser
        fields = ('firstname', 'lastname', 'company', 'email', 'phone', 'password')

    def clean_email(self):
        email = self.cleaned_data['email'].lower()
        user_list = CustomUser.objects.filter(email=email)
        if user_list.count():
            raise ValidationError('There is already an account associated with that email.')
        return email

    def clean_password2(self):
        password1 = self.cleaned_data['password']
        password2 = self.cleaned_data['password2']

        if (password1 and password2) and (password1 != password2):
            raise ValidationError('Passwords do not match.')
        return password2

    def save(self, commit=True):
        context = {
            'firstname':self.cleaned_data['firstname'],
            'lastname':self.cleaned_data['lastname'],
            'email':self.cleaned_data['email'],
            'phone':self.cleaned_data['phone'],
            'password':self.cleaned_data['password'],
            'admin':'',
            'company':self.cleaned_data['company'],
        }
        custom_user = CustomUser.objects.create_user(
            context['email'],
            context['firstname'],
            context['lastname'],
            context['company'],
            context['password']
        )
        return custom_user

class CustomUserChangeForm(UserChangeForm):
    firstname = forms.CharField(label = 'First Name', max_length = 120)
    lastname = forms.CharField(label = 'Last Name', max_length = 120)
    email = forms.EmailField(label = 'New Email')
    phone = PhoneNumberField()
    old_password = forms.CharField(label = 'Current Password', min_length = 5, max_length = 50, widget = forms.PasswordInput)
    new_password = forms.CharField(label = 'New Password', min_length = 5, max_length = 50, widget = forms.PasswordInput)
    new_password2 = forms.CharField(label = 'Confirm New Password', min_length = 5, max_length = 50, widget = forms.PasswordInput)

    class Meta:
        model = CustomUser
        exclude = ['company',]

    def clean_new_password(self):
        new_password = self.cleaned_data['new_password']
        new_password2 = self.cleaned_data['new_password2']
        if (new_password and new_password2) and (new_password != new_password2):
            raise ValidationError('Passwords do not match.')
        if not (new_password and new_password2):
            raise ValidationError('Please enter new password twice.')

        return new_password

    def clean_email(self):
        email = self.cleaned_data['email']
        email_list = CustomUser.objects.filter(email=email)
        if email_list.count():
            raise ValidationError('There is already an account associated with that email.')

        return email
Run Code Online (Sandbox Code Playgroud)

我希望能够正确迁移数据库并在我的站点上使用我的自定义用户模型(即允许用户使用我概述的自定义字段注册和创建配置文件)。相反,当尝试在命令提示符中运行迁移时,我收到了上面显示的错误。

任何帮助表示赞赏!谢谢!

Dan*_*man 27

就像错误所说的那样,默认情况下,用户的管理类按用户名排序。由于您没有用户名,您应该覆盖它:

class CustomUserAdmin(BaseUserAdmin):
    ...
    ordering = ('email',)
Run Code Online (Sandbox Code Playgroud)