如何在Django管理员中创建TabularInline?

时间:2013-05-14 12:39:46

标签: django admin

我想要Django admin中的TabularInline字段是必需的。我该怎么办?这是我的代码:

admin.py

class SchoolInline(TabularInline):
    model = School.labs.through
    extra = 1

class LaboratoryAdmin(ModelAdmin):
    inlines = [SchoolInline]

register(Lab, LaboratoryAdmin)

我简化了很多问题,但基本上就是这样。结果我得到了所有学校的下拉列表。问题是这个字段不是必需的,但我希望它是必需的。我怎样才能以最简单的方式做到这一点?

1 个答案:

答案 0 :(得分:3)

forms.py

# One form required
from django.core.exceptions import ValidationError
from django.forms.models import BaseInlineFormSet    

class AtLeastOneFormSet(BaseInlineFormSet):
    def clean(self):
        super(AtLeastOneFormSet, self).clean()
        non_empty_forms = 0
        for form in self:
            if form.cleaned_data:
                non_empty_forms += 1
        if non_empty_forms - len(self.deleted_forms) < 1:
            raise ValidationError("Please fill at least one form.")

forms.py

# First form not empty and can not be deleted
from django.forms.models import BaseInlineFormSet    

class RequiredInlineFormSet(BaseInlineFormSet):
    def _construct_form(self, i, **kwargs):
        form = super(RequiredInlineFormSet, self)._construct_form(i, **kwargs)
        if i < 1:
            form.empty_permitted = False
        return form

您还需要更改视图并删除第一个表单的delete按钮,如下所示: https://docs.djangoproject.com/en/dev/topics/forms/formsets/#manually-rendered-can-delete-and-can-order

admin.py

from django.contrib.admin import TabularInline

class SchoolInline(TabularInline):
    model = School.labs.through
    extra = 1
    formset = RequiredInlineFormSet # or AtLeastOneFormSet