1

在 Django 中,您可以clean向表单添加一个方法来验证相互依赖的字段:

def clean_recipients(self):
    data = self.cleaned_data['recipients']
    if "fred@example.com" not in data:
        raise ValidationError("You have forgotten about Fred!")

    # Always return a value to use as the new cleaned data, even if
    # this method didn't change it.
    return data

如何使用干净的方法向Wagtail ModelAdmin添加自定义表单?

Wagtail 具有panels概念并动态构建表单。我找不到任何关于覆盖表单的信息。有关于自定义创建和更新视图的信息。自定义视图似乎有点麻烦。

4

1 回答 1

1

我通过 Wagtail Slack 表单 @CynthiaKiser 得到了答案。

base_form_class允许您在模型上设置a WagtailAdminModelForm

from wagtail.admin.forms import WagtailAdminModelForm

class Foo(models.Model):
    ...
    base_form_class = FooForm


class FooForm(WagtailAdminModelForm):
    def clean(self):
        data = self.cleaned_data['recipients']
        if "fred@example.com" not in data:
            raise ValidationError("You have forgotten about Fred!")
        return data

您在 Wagtail 中遇到的所有 CRUD 表单都只是下面的 Django ModelForm 实例,因此这些 Django 文档是相关的(感谢@ababic)

另一种base_form_class方法是在模型上指定一个干净的方法。它将以任何形式调用。

from django.core.exceptions import ValidationError

class Foo(models.Model):
    ...
    def clean(self):
        if "fred@example.com" not in self.recipients:
            raise ValidationError(
                {'recipients': _("You have forgotten about Fred!")}
            )
于 2021-08-09T21:53:55.600 回答