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