gpt4 book ai didi

Wagtail ModelAdmin 清理和验证相互依赖的字段

转载 作者:行者123 更新时间:2023-12-05 03:39:05 26 4
gpt4 key购买 nike

在 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 具有面板 概念并动态构建表单。我找不到任何关于覆盖表单的信息。有关于自定义创建和更新 View 的信息。自定义 View 似乎有点麻烦。

最佳答案

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

base_form_class 允许您在模型上设置 WagtailAdminModelForm

from wagtail.admin.forms import WagtailAdminModelForm

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


class FooForm(WagtailAdminModelForm): # For pages use WagtailAdminPageForm
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 实例,所以 these Django docs are relevant (感谢@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!")}
)

关于Wagtail ModelAdmin 清理和验证相互依赖的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68718536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com