如何使用 ModelMultipleChoiceField 而不是整个查询集在每个对象上运行 django 表单验证器

发布于 2025-01-11 06:35:05 字数 681 浏览 0 评论 0原文

我有一个模型,它生成一系列复选框以将子部件添加到父部件。我创建了一个检查循环关系的验证器。然而,我目前收到错误,因为“propose_child”是一个查询集,其中包含用户选择的多个值。如何让这个验证器在该查询集中的每个对象上运行?

    def __init__(self, qs, part, *args, **kwargs):
        super(AddPartToAssemblyForm, self).__init__(*args, **kwargs)
        self.part = part
        self.fields['children'] = forms.ModelMultipleChoiceField(
            queryset=qs,
            widget=forms.CheckboxSelectMultiple
        )

    def clean_children(self):
        proposed_child = self.cleaned_data['children']
        part = self.part
        validate_acyclic_relationship(part, proposed_child)

    class Meta:
        model = Part
        fields = ['children']

I have a modelform which generates a series of checkboxes to add children to a parent part. I have created a validator that checks for cyclic relationships. I'm currently getting errors however because "proposed_child" is a queryset containing however many values the user has selected. How do I have this validator run on each object in that queryset?

    def __init__(self, qs, part, *args, **kwargs):
        super(AddPartToAssemblyForm, self).__init__(*args, **kwargs)
        self.part = part
        self.fields['children'] = forms.ModelMultipleChoiceField(
            queryset=qs,
            widget=forms.CheckboxSelectMultiple
        )

    def clean_children(self):
        proposed_child = self.cleaned_data['children']
        part = self.part
        validate_acyclic_relationship(part, proposed_child)

    class Meta:
        model = Part
        fields = ['children']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

这样的小城市 2025-01-18 06:35:05

我想通了,我将 propose_child 更改为 proposechildren 并更改了我的验证器,以便它迭代接收的查询集并依次验证每个对象。

现在我有工作验证器,但如果数据有效,则表单不会返回 form.cleaned_data['children'] 中的任何内容

--edit--

需要 return suggest_childrenclean_children 的末尾

I figured it out, I changed proposed_child to proposed children and changed my validator so that it iterates through the queryset it receives and validates each object in turn.

Now I have working validator but if the data is valid the form isn't returning anything in form.cleaned_data['children']

--edit--

needed to return proposed_children at the end of clean_children

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文