在Django admin.py中创建模型的新实例时出错

时间:2019-05-05 16:38:15

标签: python django

我在用户应用中的admin.py有问题。 我尝试在django的管理面板中创建一个新用户,但出现此错误:

Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class UserAdmin.

但是字段用户名实际上不存在。并且我已经创建了自定义用户管理器,并在模型中设置了 REQUIRED_FIELDS =“电子邮件”

如您所见,我已经在下方添加了 add_fieldsets 。错误消失了,但是管理面板仍然需要用户名而不是电子邮件。

UserAdmin:

class UserAdmin(UserBaseAdmin):
    list_display = ["email", "first_name", "last_name", "is_active"]
    list_filter = ["is_active", "is_admin", "is_staff"]
    search_fields = ["first_name", "last_name", "email"]
    ordering = ["email"]

    add_fieldsets = (
        (None, {"fields": ("first_name", "last_name", "email", "password")}),
        ("Permissions", {"fields": ("is_admin", "is_staff", "is_active")})
    )

    fieldsets = (
        (None, {"fields": ("first_name", "last_name", "email", "password")}),
        ("Permissions", {"fields": ("is_admin", "is_staff", "is_active")})
    )

    filter_horizontal = []


admin.site.register(User, UserAdmin)

型号:

class User(AbstractBaseUser, UserTimeStamp):
    first_name  = models.CharField(max_length=50, blank=False, null=False)
    last_name   = models.CharField(max_length=100, blank=False, null=False)
    email       = models.EmailField(unique=True, blank=False, null=False)
    is_admin    = models.BooleanField(default=False, blank=False, null=False)
    is_staff    = models.BooleanField(default=False, blank=False, null=False)
    is_active   = models.BooleanField(default=True, blank=False, null=False)

    objects     = UserManager()

    USERNAME_FIELD = "email"

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, perm_label):
        return True

用户经理:

class UserManager(BaseUserManager):
    def get_queryset(self, *args, **kwargs):
        return UserQueryset(self.model, using=self._db)

    def create_user(self, email,password=None):
        if not email:
            raise ValueError("Users must have an email address.")
        user = self.model(email=self.normalize_email(email))
        user.set_password(password)  
        try:
            user.save(using=self._db)
            return user
        except:
            raise ValueError("Couldn't create user")

0 个答案:

没有答案