在我的应用程序中,我有一些模型,分别是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,)
我已经在formset级别进行了验证,但现在我想为每个内联设置一些验证。为此,我添加了以下内容:
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级别验证时它可以正常工作。但它在Form级别上并不相同。有没有想过修复内联表单验证?