1

我希望 Django 管理中的 TabularInline 字段是必需的。我该如何进行?这是我的代码:

管理员.py

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

class LaboratoryAdmin(ModelAdmin):
    inlines = [SchoolInline]

register(Lab, LaboratoryAdmin)

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

4

1 回答 1

4

表格.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.")

表格.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-可以订购

管理员.py

from django.contrib.admin import TabularInline

class SchoolInline(TabularInline):
    model = School.labs.through
    extra = 1
    formset = RequiredInlineFormSet # or AtLeastOneFormSet
于 2013-05-14T19:23:46.517 回答