Django Admin内联显示去掉多余行
- Django Admin可以设置内联显示,让有外键依赖的Model再同一个页面显示。
# admin.py
# Case为Result的外键
# 相同于 一个Case下,有多个Result
class ResultInline(admin.TabularInline):
model = Result
class CaseAdmin(admin.ModelAdmin):
inlines = [ResultInline]
admin.site.register(Case, CaseAdmin)
- 上面的代码,可以让Django Admin管理 Case时,可以显示隶属于该Case的Result。
- 实际运行起来时,发现在Case管理页面,显示Result的部分,会多出几个空白行。而且,这几行没法删除,如果点击Save,会把这几个当成Result,保存进去。
- 修改,将extra设置为0即可。
class ResultInline(admin.TabularInline):
model = Result
extra = 0 # 将额外的行设置为0,即可
- 关于extra解释如下
- https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.extra
InlineModelAdmin.extra
This controls the number of extra forms the formset will display in addition to the initial forms. See the formsets documentation for more information.
For users with JavaScript-enabled browsers, an “Add another” link is provided to enable any number of additional inlines to be added in addition to those provided as a result of the extra argument.
The dynamic link will not appear if the number of currently displayed forms exceeds max_num, or if the user does not have JavaScript enabled.