如何使用 ModelMultipleChoiceField 而不是整个查询集在每个对象上运行 django 表单验证器
我有一个模型,它生成一系列复选框以将子部件添加到父部件。我创建了一个检查循环关系的验证器。然而,我目前收到错误,因为“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想通了,我将
propose_child
更改为proposechildren
并更改了我的验证器,以便它迭代接收的查询集并依次验证每个对象。现在我有工作验证器,但如果数据有效,则表单不会返回
form.cleaned_data['children']
中的任何内容--edit--
需要
return suggest_children
在clean_children
的末尾I figured it out, I changed
proposed_child
toproposed 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 ofclean_children