如何在tabularinline块的每一行中添加行号 [英] How to add a line number to each row of a tabularinline block

查看:74
本文介绍了如何在tabularinline块的每一行中添加行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ModelAdmin类,其内联类型为TabularInline.我想为TabularInline的每一行在其左侧显示一个行号.该数字将随着新记录添加到内联中而增加,并在编辑表单时显示.

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.

我更喜欢行号不是内联数据模型的一部分,而是在每次将新记录添加到内联块或由内联块显示时生成.我不需要将此号码保留在数据库中.仅在ModelAdmin类的另一个字段上提供参考.

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.

我是django的新手,我似乎无法弄清楚如何做到这一点.

I'm new to django, and I can't seem to figure out how to make this happen.

任何建议将不胜感激.

关于,里克

推荐答案

您可以通过admin类使用类变量和返回行号的方法轻松地对现有内联进行编号:

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.

这篇关于如何在tabularinline块的每一行中添加行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆