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.