pythondjangodjango-admin

Fieldsets don't do anything in admin django


I'm learning Django and found that we can use fieldsets to customise the way admin creation form looks like. Here is the code I'am using:

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    
    list_display = ('email', 'age', 'is_staff', 'is_active',)
    list_filter = ('email', 'age', 'is_staff', 'is_active',)

    fieldsets = (
        ('Advanced options', {
            'classes': ('wide',),
            'fields': ('email', 'age', 'is_staff', 'is_active',),
        }),
    )
    

admin.site.register(CustomUser, CustomUserAdmin)

Here is the result:

enter image description here

As you can see this "fieldsets" does nothing for this creation page. And if I completely remove this "fieldsets" nothing will change. What I did wrong here? I want my fieldsets work.

Thank you!


Solution

  • The UserAdmin separates the add action (user creation) form other actions. This is because it only wants to deal with username and password and then the rest of the fields.

    So the UserAdmin does some special work and you have both fieldsets and add_fieldsets.

    Below is copied from a customer user in one of my projects. It has a required field on the User model called display_name and so it must be submitted via the admin as well.

    from django.contrib import admin
    from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
    from django.utils.translation import gettext as _
    
    from core import models
    from core.forms.admin import UserCreationForm
    
    
    @admin.register(models.User)
    class UserAdmin(AuthUserAdmin):
        fieldsets = (
            (None, {"fields": ("username", "password")}),
            (_("Personal info"), {"fields": ("display_name", "email")}),
            (
                _("Permissions"),
                {
                    "fields": (
                        "is_active",
                        "is_staff",
                        "is_superuser",
                        "groups",
                        "user_permissions",
                    ),
                },
            ),
            (_("Important dates"), {"fields": ("last_login", "date_joined")}),
        )
        add_fieldsets = (
            (
                None,
                {"classes": ("wide",), "fields": ("username", "password1", "password2"),},
            ),
            (_("Profile related"), {"fields": ("display_name",)}),
        )
        add_form = UserCreationForm