Django Form fields changing after page refresh

44 Views Asked by At

The first time I open this ModelAdmin's /add page, all the fields of the ServiceProvider model are displayed, although I specified with self.fields the fields that should be displayed. When pressing F5 to reload the page, the unsolicited fields do not appear. I suspected cache, but disabling the caches did not cause changes. The problem with loading all fields is that it also does some heavy querying related to those fields.

class ServiceProviderAdmin(admin.ModelAdmin):
    ...
    def get_form(self, request, obj=None, **kwargs):
        self.fields = (
            "name_registration",
            "name_social",
            "nome_usual",
            ("gender","document"),
            "department",
            "department_aditionals",
            "picture",
            "active",
        )
        if request.user.has_perm("rh.can_edit_secondary_mail"):
            self.fields = self.fields + ("email_secondary",)

        self.form = ServiceProviderFormFactory(request.user)
        return super().get_form(request, obj=obj, **kwargs)


def ServiceProviderFormFactory(user):
    class ServiceProviderForm(forms.ModelForm):
        ...

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            ...

        class Meta:
            model = ServiceProvider
            exclude = ("",)
1

There are 1 best solutions below

0
Neto On

I managed to resolve this. The ModelAdmin fields were being set in the get_form method, but it seems that on first access, Django fetches the list of fields before getting to the get_form method. As the list of fields was not yet defined, it got all the fields related to the model. Changing the fields definition from get_form to get_fields solved the problem:

class ServiceProviderAdmin(admin.ModelAdmin):
    ...
    def get_fields(self, request, obj=None):
        fields = (
            "name_registration",
            "name_social",
            "nome_usual",
            ("gender","document"),
            "department",
            "department_aditionals",
            "picture",
            "active",
        )
        if request.user.has_perm("rh.can_edit_secondary_mail"):
            fields = fields + ("email_secondary",)

        return fields