Search code examples
pythondjangoadmin

Dynamically change field of Django admin inline form


I want to dynamically change a CharField to a ChoiceField, because I want the value to be selected from a list of possibilities that is determined by the current request.

In a ModelAdmin I can do that with get_form(), and just say:

form.base_fields[field_name] = forms.ChoiceField(...)

but how can I do the same for an InlineModelAdmin (TabularInline)? I stepped a bit through get_formset() and get_fieldsets() but can't find the right spot for hooking in.


Solution

  • There's a get_formsets method you can use like get_form for the inlines. This is the default version from django.contrib.admin.options.ModelAdmin:

    def get_formsets(self, request, obj=None):
        for inline in self.inline_instances:
            yield inline.get_formset(request, obj)