13👍
The ‘fieldsets +’ approach is much better than having to write out all the default fields again.
fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('some_extra_data',)}),
)
13👍
Andy try adding this to your admin class:
fieldsets = (
(('User'), {'fields': ('username', 'email','is_staff', 'bio')}),
)
You can also add other sets for example another section that is all about permissions, and can display information about is_active, or groups. You can do this:
fieldsets = (
(('User'), {'fields': ('username', 'email','is_staff', 'bio')}),
(('Permissions'), {'fields': ('is_active','is_staff')}),
)
You can just insert fieldsets underneath list_display. There is also a readonly_fields for fields that you do not want to be editable in the admin.
- How do I generate models for an existing database in Django?
- How do I extend the Django "login" form?
2👍
To add a "bio" field to the "Personal info" section instead of just to the end of the User admin, and to do so without specifying every existing field, you can construct a new fieldsets
attribute from the parent class while only adding the new "bio" field to the "Personal info" section and preserving everything else.
If you simply append to the parent’s fieldsets
attribute, then the field will appear at the bottom of the page and not at the end of the "Personal info" section.
This code makes a copy of the parent’s fieldsets
attribute with everything preserved as-is except that the fields
tuple in the "Personal info" section has "bio" appended.
in users/admin.py
:
class CustomUserAdmin(UserAdmin):
# Add a "bio" field to the User admin page.
fieldsets = tuple(
# For the "Personal info" fieldset, drill down to the fields,
# preserving everything else.
(fieldset[0], {
# Preserve any entries in the dict other than "fields".
**{key: value for (key, value) in fieldset[1].items() if key != 'fields'},
# Add the "bio" field to the existing fields
'fields': fieldset[1]['fields'] + ('bio',)
})
# Preserve any fieldsets other than "Personal info".
if fieldset[0] == 'Personal info'
else fieldset
for fieldset in UserAdmin.fieldsets
)
Note: The {**some_dict, new_key: new_value}
syntax requires Python 3.5 or greater.
- Django form with unknown number of checkbox fields and multiple actions
- How can I use server-side cursors with django and psycopg2?
- Assign Value of Named URL to a Variable in Django Templates