custom User model with auto_now_add=True causes “non-editable field” Exception in UserAdmin

懵懂的女人 提交于 2021-02-08 10:01:11

问题


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.

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

I am using the default Django AdminModel:

class UserAdminModel(UserAdmin):
    pass

回答1:


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:

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. Either you make the change explicit, by telling Django it is indeed not meant to be editable:
class UserAdminModel(UserAdmin):
    readonly_fields = ["date_joined"]
  1. Or revert your change, going back to the Django default of having that field editable:
class UserProfile(AbstractBaseUser, PermissionsMixin):
    # [..]
    date_joined = models.DateTimeField(default=timezone.now)

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.



来源:https://stackoverflow.com/questions/57249404/custom-user-model-with-auto-now-add-true-causes-non-editable-field-exception-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!