如何修复 dajango 自定义用户模型中 admin.py 中的不可调用属性错误?

how to fix not a callable attribute error in admin.py in custom user model in dajango?

我只是想获得自定义用户模型。当我在 model.py 中创建用户 class 并在 forms.py 中创建表单时,服务器 运行 正常。但是在 admin.py 中创建 UserAdmin class 之后,我收到了一个不可归类的属性错误。即使我没有任何名为 first_name 或 last_name 的属性,我也不需要它们。那么如何消除该错误?

//admin.py

    User=get_user_model()
class UserAdmin(BaseUserAdmin):
    add_form=UserCreationForm

    list_dispalay=('username','email','is_admin',)
    list_filter=('is_admin',)

    fieldsets=(
            (None,{'fields':('username','email','password')}),
            ('permissions',{'fields':('is_admin',)})
        )
    search_fields=('username','email')
    ordering=('username','email')
    filter_horizontal=()





admin.site.register(User,UserAdmin)
admin.site.unregister(Group)

//forms.py

    User=get_user_model()
class UserCreationForm(forms.ModelForm):

    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model=User
        fields=['username','email']

    def clean_password(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class UserLoginForm(forms.Form):
    query=forms.CharField(label='Username/Email')
    password=forms.CharField(label='Password',widget=forms.PasswordInput)

    def clean(self,*args,**kwargs):
        query=self.cleaned_data.get('query')
        password=self.cleaned_data.get('password')
        user_qs_final=User.objects.filter(
                Q(username__iexact=query)|
                Q(email__iexact=query)
            ).distinct()
        if not user_qs_final.exists() and user_qs_final!=1:
            raise forms.ValidationError("Invalid credentials-user does not exits")
        user_obj=user_qs_final.first()
        if not user_obj.check_password(password):
            raise forms.ValidationError("credential are wrong")
        self.cleaned_data["user_obj"]=user_obj
        return super(UserLoginForm,self).clean(*args,**kwargs)

//models.py

 class UserManager(BaseUserManager):
    use_in_migrations = True
    def create_user(self,username,email,password=None,is_admin=False,is_survilance=True,is_staff=False):
        #if not email:
            #raise ValueError('user must have email address')
        user_obj=self.model(
            username=username,
            email=self.normalize_email(email),
            is_admin = is_admin,
            is_survilance = is_survilance,
            is_staff = is_staff,
        )
        user_obj.set_password(password)

        user_obj.save(using=self._db)
        return user_obj

    def create_superuser(self,username,email,password):
        user_obj=self.create_user(
            username,email,password,is_admin=True,is_staff=True
        )

        user_obj.save(using=self._db)
        return user_obj


class User(AbstractBaseUser):
    username=models.CharField(max_length=30,unique=True, null=False, blank=False)
    email=models.EmailField(max_length=255,unique=True)
    is_admin=models.BooleanField(default=False)
    is_survilance=models.BooleanField(default=True)
    is_active =models.BooleanField(default=True)
    is_staff = models.BooleanField(default=True)
    objects=UserManager()
    USERNAME_FIELD='username'
    REQUIRED_FIELDS=['email']

    class Meta:
        app_label = "articles"
        db_table = "users"

    def __str__(self):
        return self.username

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

    # this methods are require to login super user from admin panel
    def has_perm(self, perm, obj=None):
        return self.is_staff

    # this methods are require to login super user from admin panel
    def has_module_perms(self, app_label):
        return self.is_staff

我在 运行 服务器时收到此错误 错误:

    <class 'articles.admin.UserAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'first_name', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'articles.User'.
    <class 'articles.admin.UserAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'last_name', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'articles.User'.

您打错了:list_dispalay 应该是 list_display


至于为什么会导致错误:您的 UserAdmin subclasses BaseUserAdmin,您很可能按如下方式导入:

from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

如果您在 source code 中查找 class,您会注意到:

list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')

由于您的 属性 名称不正确,它会选择原始值并查找这些字段。