Django在两个字段之间形成自定义验证(Django forms custom validation on two fields one or the other)

编程入门 行业动态 更新时间:2024-10-26 18:16:16
Django在两个字段之间形成自定义验证(Django forms custom validation on two fields one or the other)

我正在努力解决以下问题,需要一些指导,下面你会看到我的form.py。 我有两个名为group和single字段。 我需要对他们应用以下规则/验证...

用户必须输入一个号码或选择至少一个组,但从来都不是

所以用户不能同时选择一个组和一个号码,但他们必须有一个或另一个。 希望这是有道理的?

由于这些规则,我不能只添加required = true并需要某种自定义验证。 这是我自己有问题的自定义验证。

任何人都可以根据我需要的验证形式给我一个例子吗?

谢谢。

Forms.py

class myForm(forms.ModelForm): def __init__(self, user=None, *args, **kwargs): super(BatchForm, self).__init__(*args, **kwargs) if user is not None: form_choices = Group.objects.for_user(user).annotate(c=Count('contacts')).filter(c__gt=0) else: form_choices = Group.objects.all() self.fields['group'] = forms.ModelMultipleChoiceField( queryset=form_choices, required=False ) self.fields['single'] = forms.CharField(required=False)

I'm struggling with the following and need some guidance, below you will see my form.py. I have two fields called group and single. I need to apply the following rules/validation to them...

A user must either enter a single number or select at least one group but never both

So a user can never select both a group and a enter a single number at the same time, but they must have one or the other. Hope that makes sense?

Because of these rules I cannot just add required = true and need some sort of custom validation. It's this custom validation I''m having problems with.

Could anyone give me an example based on my form of the sort of validation I would need?

Thanks.

Forms.py

class myForm(forms.ModelForm): def __init__(self, user=None, *args, **kwargs): super(BatchForm, self).__init__(*args, **kwargs) if user is not None: form_choices = Group.objects.for_user(user).annotate(c=Count('contacts')).filter(c__gt=0) else: form_choices = Group.objects.all() self.fields['group'] = forms.ModelMultipleChoiceField( queryset=form_choices, required=False ) self.fields['single'] = forms.CharField(required=False)

最满意答案

你需要在窗体的clean方法中处理它。 像这样的东西:

class BatchForm(forms.ModelForm): ... ... def clean(self): check = [self.cleaned_data['single'], self.cleaned_data['group']] if any(check) and not all(check): # possible add some errors return self.cleaned_data raise ValidationError('Select any one')

You need to handle that in the form's clean method. Something like this:

class BatchForm(forms.ModelForm): ... ... def clean(self): check = [self.cleaned_data['single'], self.cleaned_data['group']] if any(check) and not all(check): # possible add some errors return self.cleaned_data raise ValidationError('Select any one')

更多推荐

本文发布于:2023-07-09 14:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1086998.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   字段   两个   Django   fields

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!