Search code examples
djangodjango-admindjango-authentication

Django use edit form as add user gives error


I'm using Django 2.2.x.

I want to use all fields which are in the edit user form to the add user form. For that I have extended AuthUserAdmin

@admin.register(User)
class UserAdmin(AuthUserAdmin):

    inlines = [
        ProfileAdminInline
    ]

    fieldsets = AuthUserAdmin.fieldsets
    add_fieldsets = AuthUserAdmin.fieldsets

    list_filter = [
        'is_staff',
        'is_active',
        'is_superuser',
        'last_login',
        'date_joined',
    ]

    list_display = [
        'email',
        'full_name',
        'is_staff',
        'is_superuser',
        'is_active',
        'last_login',
        'date_joined',
    ]

    ordering = ('-date_joined', 'username',)

    search_fields = ['email', 'first_name', 'last_name']

But adding user gives error

Please correct the errors below

But no field is highlighted for the error.

How can I use edit form as add form in Django admin add user?


Solution

  • add_fieldsets includes password1 and password2.

        add_fieldsets = (
            (None, {
                'classes': ('wide',),
                'fields': ('username', 'password1', 'password2'),
            }),
        )
    

    So you can't replace it with fieldsets, which has password.

        fieldsets = (
            (None, {'fields': ('username', 'password')}),
            ...
    

    You could try combining them as follows:

        # You can remove 'fieldsets' since it will 
        # inherit AuthUserAdmin.fieldsets by default
        fieldsets = AuthUserAdmin.fieldsets
        add_fieldsets = AuthUserAdmin.add_fieldsets + AuthUserAdmin.fieldsets[1:]
    

    That will solve the error, but I don't think it will work, because the user admin has:

    add_form = UserCreationForm
    

    You'll need to create a custom form with the extra fields you want.