[Django]-How do I dynamically set max_num for a django TabularInline based on a value from a foreign table?

7👍

You can override get_max_num in PortInLineAdmin:

class PortInLineAdmin(admin.TabularInline):
    model = Port
    extra = 8

    def get_max_num(self, request, obj=None, **kwargs):
        return obj.model.port_count

In Django 1.5 you need a different trick:

class PortInLineAdmin(admin.TabularInline):
    model = Port
    extra = 8

    def get_formset(self, request, obj=None, **kwargs):
        self.max_num = obj.model.port_count
        return super(PortInLineAdmin, self).get_formset(request, obj, **kwargs)

0👍

Or just:

class YourModelLin(TabularLin):
model = YourModel
....

def get_max_num(self, request, obj=None, **kwargs):
    return obj.yourmodel_set.count() + 1

It works perfectly in django 2.2 🙂

👤Abel

Leave a comment