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