问题
I have a ModelAdmin class with an inline of type TabularInline. What I would like is for each row of the TabularInline to have a line number displayed to the left of it. This number would increment as new records are added to the inline, and would be displayed when the form is being edited.
I prefer the line number not be a part of the model for the inlined data, but rather be generated each time a new record is added to or displayed by the inline block. I don't need to keep this number in the database. It is for reference only on another field in the ModelAdmin class.
I'm new to django, and I can't seem to figure out how to make this happen.
Any suggestions would be appreciated.
Regards, Rick
回答1:
You can number existing inlines easily through the admin class with a class variable and a method to return the line number:
class MyInlineAdmin(admin.TabularInline):
line_numbering = 0
fields = ('line_number', 'other_field')
readonly_fields = ('line_number',)
def line_number(self, obj):
self.line_numbering += 1
return self.line_numbering
line_number.short_description = '#'
This will number any inlines in the order they appear, including any extra (blank) inlines that are included. If you add a single inline via the "Add another" link, it's line number will be correct (incremented by one from the last one), however if you add more than one inline via the link, subsequent ones will still have the same line number as the last one.
Not perfect, but better than nothing.
来源:https://stackoverflow.com/questions/23412602/how-to-add-a-line-number-to-each-row-of-a-tabularinline-block