For the django admin, how do I add a field to the User model and have it editable in the admin?

后端 未结 5 1257
闹比i
闹比i 2021-02-04 10:42

I\'m trying to understand the django admin better and at the same time, I\'m trying to add one more field to the current user admin. In models.py I\'ve done

Use         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-04 10:55

    Just figured this out, perhaps this could help you as well.

    Since you don't mention that you have a separate profile, if you want to simply add a column to the existing User admin, you can do the following in admin.py:

    First you create a custom admin by subclassing UserAdmin:

    class CustomUserAdmin(UserAdmin):
        list_display = UserAdmin.list_display + ('is_complete',)
    
        def is_complete(self, obj):
            # Example here, you can use any expression.
            return SomeOtherClass.objects.get(my_field=obj).is_complete()
    
        # Not required, but this gives you a nice boolean field:
        is_complete.boolean = True
    

    Then unregister the existing UserAdmin and register your own:

    admin.site.unregister(User)
    admin.site.register(User, CustomUserAdmin)
    

提交回复
热议问题