Dynamic fields in Django Admin

Stephan Hoyer picture Stephan Hoyer · Nov 4, 2011 · Viewed 17k times · Source

I want to have additional fields regarding value of one field. Therefor I build a custom admin form to add some new fields.

Related to the blogpost of jacobian 1 this is what I came up with:

class ProductAdminForm(forms.ModelForm):
    class Meta:
        model = Product

    def __init__(self, *args, **kwargs):
        super(ProductAdminForm, self).__init__(*args, **kwargs)
        self.fields['foo'] = forms.IntegerField(label="foo")

class ProductAdmin(admin.ModelAdmin):
    form = ProductAdminForm

admin.site.register(Product, ProductAdmin)

But the additional field 'foo' does not show up in the admin. If I add the field like this, all works fine but is not as dynamic as required, to add the fields regarding the value of another field of the model

class ProductAdminForm(forms.ModelForm):

    foo = forms.IntegerField(label="foo")

    class Meta:
        model = Product

class ProductAdmin(admin.ModelAdmin):
    form = ProductAdminForm

admin.site.register(Product, ProductAdmin)

So is there any initialize method that i have to trigger again to make the new field working? Or is there any other attempt?

Answer

Stephan Hoyer picture Stephan Hoyer · Nov 5, 2011

Here is a solution to the problem. Thanks to koniiiik i tried to solve this by extending the *get_fieldsets* method

class ProductAdmin(admin.ModelAdmin):
    def get_fieldsets(self, request, obj=None):
        fieldsets = super(ProductAdmin, self).get_fieldsets(request, obj)
        fieldsets[0][1]['fields'] += ['foo'] 
        return fieldsets

If you use multiple fieldsets be sure to add the to the right fieldset by using the appropriate index.