1
votes

Currently i have this user proxy model:

class UserProxy(User):

    class Meta:
        verbose_name = 'Staff'
        verbose_name_plural = 'Staffs'
        proxy = True

And on the admin side i have the following admin like so:

class StaffAdmin(UserAdmin):
    def get_queryset(self, request):
        qs = super(StaffAdmin, self).get_queryset(request)
        return qs.filter(is_staff=True)

    exclude = ('first_name', 'last_name',)

    def save_model(self, request, obj, form, change):
        if request.user.is_superuser:
            obj.is_staff = True
            obj.save()
admin.site.register(UserProxy, StaffAdmin)

When i go to any form of the proxy model on admin it return the following error:

"Key 'first_name' not found in 'UserProxyForm'. Choices are: date_joined, email, groups, is_active, is_staff, is_superuser, last_login, password, user_permissions, username."

I figured that was weird and i tried to only exclude is_staff and now it return:

"Key 'is_staff' not found in 'UserProxyForm'. Choices are: date_joined, email, first_name, groups, is_active, is_superuser, last_login, last_name, password, user_permissions, username."

Why is this happening ? isn't the proxy model should have all the fields from base model ?

1
Can you share code for UserAdmin?ChillarAnand
UserAdmin is from django.contrib.auth.admin @ChillarAnandLinh Nguyen

1 Answers

3
votes

After reading over django UserAdmin class https://github.com/django/django/blob/master/django/contrib/auth/admin.py#L45

It seems like UserAdmin use fieldsets and don't use exclude, i rewrite my StaffAdmin to:

class StaffAdmin(UserAdmin):

    def get_queryset(self, request):
        qs = super(StaffAdmin, self).get_queryset(request)
        return qs.filter(is_staff=True)

    list_display = ('username', 'email', 'is_staff')
    search_fields = ('username', 'email')
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('email',)}),
        (_('Permissions'), {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups'),
        }),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )

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

    def save_model(self, request, obj, form, change):
        if request.user.is_superuser:
            obj.is_staff = True
            obj.save()
admin.site.register(UserProxy, StaffAdmin)

And now i can define which fields need to be display