【问题标题】:Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin为用户指定的未知字段(用户名)。检查 CustomUserAdmin 类的字段/字段集/排除属性
【发布时间】:2020-11-28 12:21:58
【问题描述】:

为我的 python django 应用程序创建自定义用户后,我开始收到标题中所述的错误。只有当我不想从管理面板添加新用户时才会发生这种情况,这时我收到错误“为用户指定的未知字段(用户名)。检查 CustomUserAdmin 类的字段/字段集/排除属性。”我曾尝试在互联网上到处寻找答案,但没有运气。 管理员.py:

# accounts/admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import User

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = User
    list_display = ['email', 'first_name','last_name', 'image',  'country_code','country', 'phone','state_province','city_town','address', 'postal_code',]
    add_fieldsets = UserAdmin.add_fieldsets + (
        (None, {'fields': ('email', 'first_name', 'last_name',  'image', 'country_code','country', 'phone','state_province','city_town','address', 'postal_code',)}),
    )
    fieldsets = (
        (None, {
            "fields": (
                ('email', 'first_name', 'last_name', 'image', 'is_staff',  'country_code','country', 'phone','state_province','city_town','address', 'postal_code',)
                
            ),
        }),
    )
    search_fields = ('email', 'first_name', 'last_name')
    ordering = ('email',)
    
admin.site.register(User, CustomUserAdmin)

models.py:

    from django.contrib.auth.models import AbstractUser, BaseUserManager ## A new class is imported. ##
from django.db import models
from django_countries.fields import CountryField
from django.utils.translation import ugettext_lazy as _



from django.contrib.auth.models import AbstractUser
from django.db import models


class UserManager(BaseUserManager):
    """Define a model manager for User model with no username field."""

    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """Create and save a User with the given email and password."""
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        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, **extra_fields):
        """Create and save a SuperUser with the given email and password."""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)




class User(AbstractUser):
    username = None
    email = models.EmailField(_('email address'), unique=True)
    country_code = models.CharField(max_length=250)
    phone = models.IntegerField(unique=True, null=True)
    country = CountryField(max_length=250)
    state_province = models.CharField(max_length=250)
    city_town = models.CharField(max_length=250)
    address = models.CharField(max_length=250)
    postal_code = models.CharField(max_length=250)
    image = models.ImageField(default='default.png')


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = UserManager() ## This is the new line in the User model. ##
    # add additional fields in here

    def __str__(self):
        return self.email

【问题讨论】:

    标签: django django-admin django-custom-user


    【解决方案1】:

    在我的 app/admin.py CustomeUserAdmin 类中添加以下代码后,它对我有用:

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'first_name', 'last_name', 'password1', 'password2'),
        }),
    )
    

    在与您的自定义相关的字段中替换。

    更多信息,请阅读docs

    【讨论】:

      【解决方案2】:

      删除UserAdmin.add_fieldsets +

      这意味着扩展包含原始用户名的原始字段集。由于您的自定义用户模型没有用户名,因此会出错。

      【讨论】:

      • 嗨,我遇到了同样的问题,我的代码中没有 add_fieldsets。我在我的 User 类中继承了 AbstractBaseUser 和 PermissionsMixin。我不知道是什么导致了这个问题。
      • @Bruce,你找到答案了吗?我遇到了你描述的问题。
      • @AndréCarvalho 我更改了代码并使用了文档中的内容。这里docs.djangoproject.com/en/3.2/topics/auth/customizing/…
      • 我也有同样的问题。
      【解决方案3】:

      遇到了同样的问题,发现我在新字段的末尾缺少了一个逗号,因为它只接受一个元组:

      ('Additional info', {
              'fields': ('New Field')
          })
      

      改为:

      ('Additional info', {
              'fields': ('New Field',)
          })
      

      注意添加的逗号。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-27
        • 1970-01-01
        • 2015-02-19
        • 1970-01-01
        相关资源
        最近更新 更多