我正在努力解决以下问题,需要一些指导,下面你会看到我的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 bothSo 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')更多推荐
发布评论