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

问题描述

我正在 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'.

我被困在这里。

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

# 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
# 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
#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
# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import CustomUser
from .forms import CustomUserRegistrationForm, CustomUserChangeForm

class CustomUserAdmin(BaseUserAdmin):
    add_form = CustomUserRegistrationForm
    form = CustomUserChangeForm
    model = CustomUser

    list_display = ('firstname', 'lastname', 'email', 'company')
    list_filter = ('company',)
    fieldsets = (
        (None, {'fields': ('email', 'old_password', 'new_password', 'new_password2')}),
        ('Personal Information', {'fields': ('firstname', 'lastname', 'phone')}),
    )
    add_fieldsets = (
        (None, {'fields': ('email', 'password', 'password2')}),
        ('Personal Information', {'fields': ('firstname', 'lastname', 'phone')}),
        ('Company Information', {'fields': ('company',)}),
    )

admin.site.register(CustomUser, CustomUserAdmin)

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

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

标签: pythondjango

解决方案


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

class CustomUserAdmin(BaseUserAdmin):
    ...
    ordering = ('email',)

推荐阅读