在我的应用程序中,我有一些模型,它们各自具有 ModelAdmins 和 ModelForms ...
class Group(models.Model):
pass
class Department(models.Model):
groups = models.ManyToMany(Group, through='MyModel')
class MyModel(models.Model):
department = models.ForeignKey(
'department.Department',
related_name="group_memberships",
)
group = models.ForeignKey(
'group.Group',
related_name="department_memberships",
)
class MyModelInlineFormset(BaseInlineFormSet):
def clean(self):
# some working formset validation here
pass
class MyModelInline(admin.StackedInline):
model = MyModel
extra = 1
formset = MyModelInlineFormset
class DepartmentAdmin(ModelAdmin):
inlines = (MyModelInline,)
我已经在表单集级别进行了验证,但现在我想为每个内联设置一些验证。为此,我添加了以下内容:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def clean(self):
cleaned_data = super(GroupDepartmentMembershipForm, self).clean()
delete_checked = cleaned_data.get('DELETE')
department = cleaned_data.get('department')
group = cleaned_data.get('group')
if delete_checked:
if not group.departments.exclude(pk__exact=department.pk):
raise forms.ValidationError('orphan group!')
return cleaned_data
class MyModelInline(admin.StackedInline):
model = MyModel
extra = 1
formset = MyModelInlineFormset
form = MyModelForm
看起来不错,调试器上的行为似乎还不错,创建了 ValidationError 但它从未到达浏览器,执行的验证没有任何效果。
我发现当我在 FormSet 级别进行验证时,它可以正常工作。但在表单级别就不一样了。任何想法来修复内联表单验证?