auto_now_add = True的自定义用户模型会导致“不可编辑字段"UserAdmin中的异常 [英] custom User model with auto_now_add=True causes "non-editable field" Exception in UserAdmin

查看:59
本文介绍了auto_now_add = True的自定义用户模型会导致“不可编辑字段"UserAdmin中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习python Django.我已经创建了一个自定义用户模型,并且该模型正在运行,但是每当我通过Django admin访问任何用户的个人资料时,都会出现此错误:

I'm learning python Django. I have created a custom user model and it is working, but whenever I visit any user's profile through the Django admin I get this error:

Exception Value:    
'date_joined' cannot be specified for UserProfile model form as it is a non-editable field. Check fields/fieldsets/exclude attributes of class UserAdminModel.

这是我自定义的UserProfile模型:

This is my custom UserProfile model:

class UserProfile(AbstractBaseUser, PermissionsMixin):
    """ A model for authors and readers."""

    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    username = models.CharField(max_length=255, unique=True)
    email = models.EmailField(max_length=255, unique=True)
    password = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    date_joined = models.DateTimeField(auto_now_add=True)

    REQUIRED_FIELDS = ['email', 'password']
    USERNAME_FIELD = 'username'
    objects = UserProfileManager()

    def __str__(self):
        return self.username

我正在使用默认的Django AdminModel:

I am using the default Django AdminModel:

class UserAdminModel(UserAdmin):
    pass

推荐答案

Django Admin站点希望 date_joined 字段是可编辑的-但您的自定义用户模型不允许这样做-因为auto_now_add 始终设置当前日期.

The Django Admin site expects the date_joined field to be editable - but your custom user model does not allow that - because auto_now_add always sets the current date.

这种行为是已知的&记录:

This behavior is known & documented:

按照当前的实现,将auto_now或auto_now_add设置为True会导致该字段具有editable = False和blank = True设置.

As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set.

  1. 您可以通过告诉Django确实是

    class UserAdminModel(UserAdmin):
        readonly_fields = ["date_joined"]
    

    1. 或者还原您的更改,返回到Django默认值,使该字段可

    class UserProfile(AbstractBaseUser, PermissionsMixin):
        # [..]
        date_joined = models.DateTimeField(default=timezone.now)
    

    可能可能要走第二条路线.我尚未检查您在自定义用户模型中覆盖的其他任何字段是否与Django默认设置不兼容行政.如果您进行更改,请使其有意义,以确保进行相关表单或管理员视图的更新.

    You probably want to go the second route. I have not checked if any of the other fields you have overridden in your custom user model are incompatible with the Django default admin. If you make changes, make them meaningful enough to warrant the extra work of updating the relevant forms or admin views.

    这篇关于auto_now_add = True的自定义用户模型会导致“不可编辑字段"UserAdmin中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆