0

I think this is best understood with an example:

Pizzas and Toppings have a many to many relationship. I want to display a Pizza's toppings in a TabularInline.

class ToppingInlineAdmin(admin.TabularInline):
    model = Pizza.toppings.through
    fields = ('topping',)
    extra = 0
    if not model.topping.count():
        classes = ['collapse']

As you can see, I only want to collapse the tabular inline if there are no toppings on the pizza.

The code model.topping.count() does not work though. The error is:

AttributeError: 'ForwardManyToOneDescriptor' object has no attribute 'count'

Do you know how I can accomplish if no toppings on the pizza, collapse the tabular inline?

Thank you.

1 Answer 1

1

Firstly, model should be Toppings.

class ToppingInlineAdmin(admin.TabularInline):
    model = Toppings

To conditionally set classes on your InlineModelAdmin you need to override a method that takes the object, django does not provide a method specifically for this functionality but I have overridden get_formset as an example

def get_formset(self, request, obj=None, **kwargs):
    if not obj or not obj.toppings.count():
        self.classes = ['collapse']
    return super(ToppingInlineAdmin, self).get_formset(request, obj=obj, **kwargs)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the explanation. I appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.