5

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.

Danny W. Adair
  • 12,498
  • 4
  • 43
  • 49

2 Answers2

4

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)
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • 1
    Thanks! "formset = inline.get_formset(request, obj)" followed by "form = formset.form" and then I was able to proceed as in the ModelAdmin. – Danny W. Adair Jul 31 '12 at 09:27
  • 2
    warning seen on django code: "ModelAdmin.get_formsets() is deprecated and will be removed in Django 1.9. Use ModelAdmin.get_formsets_with_inlines() instead" – OriolJ Sep 16 '15 at 09:22
  • 1
    Just to be clear, the get_formsets will be a method of the inline class, right? For some reason get_formsets is not being called here =/ – Anoyz Feb 22 '16 at 16:05
-1

You can give a form class to the InlineModelAdmin:

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-options

or for dynamic stuff you can override the get_form method:

https://github.com/django/django/blob/master/django/contrib/admin/options.py#L431

Willian
  • 2,385
  • 15
  • 17