Daniel Daniel - 6 months ago 23
Python Question

Django TabularInline: Discard empty rows

I'm using Django

in my Admin class to show related objects from another model. I know this feature is made primarily to edit related objects on the same page, but I set the fields readonly so I have a nice table to display related objects.

Django renders a nice table but when there is only 1 related object, it renders 3 empty rows. As I don't need editing functionality, I want to only show as much rows as there are objects.

There's the two options
max_num
and
min_num
, but as the number of related objects varies in my application, I can't set this to a static value.

Is there a way I can programmatically set it to the number of related objects?

Possibly not needed for this question, but here's my code anyway:

class RirDataInline(admin.TabularInline):
model = RirData
fields = ['netname', 'inetnum', 'review_status', 'active']
readonly_fields = fields
can_delete = False
show_change_link = True


class CompanyRecordAdmin(VersionAdmin):
list_display = ('id', 'name')
search_fields = ['name']
inlines = [
RirDataInline,
]

Answer

Try to set extra to 0

class RirDataInline(admin.TabularInline):
    model = RirData
    fields = ['netname', 'inetnum', 'review_status', 'active']
    readonly_fields = fields
    can_delete = False
    show_change_link = True
    extra = 0
Comments