user3265443
user3265443

Reputation: 535

Disable/Hide unnecessary inline forms in django admin

I have model 'Product' model and many other model which have their foreign key as Product. Currently I have ProductAdmin line this

class Product:
    type_of_product=models.ChoiceField()

class ProductAdmin(admin.ModelAdmin):
    form = ProductAdminForm
    inlines = [Inline1, Inline2, Inline3, Inline4,....Inline 15]

So the Product admin add page is looking very big form. Here I need to fill only some of the models inlines depending on the value of type_of_product. So many entries of inline models are empty.

So essentially inlines are related to type_of_product attribute of Product. Current the user has to take care in which inlines he has to fill values according to what he chose as type_of_product.

Now I want to sort this out.

Option 1) Dynamic rendering of inlines forms according to what user has chosen as type_of_product through AJAX.(No idea how to do it)

Option 2) Disable or hide the unnecessary inlines so he can't see the inline forms of unrelated models.

Can anyone help to sort this out.

Upvotes: 2

Views: 2600

Answers (1)

Dariusz Aniszewski
Dariusz Aniszewski

Reputation: 457

You can modify inlines depending on current object, just override change_view method of ModelAdmin. In your ProductAdmin add something like this:

def change_view(self, request, object_id, form_url='', extra_context=None):
    product = Product.objects.get(pk=object_id)
    current_inlines = []
    # CODE TO FILL INLINES BASED ON PRODUCT
    self.inlines = current_inlines
    return super(ProductAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context)

Upvotes: 4

Related Questions