同时验证两个字段 [英] Validating two fields at the same time
问题描述
我正在看这篇文档:
https://docs.djangoproject.com/en/1.8/ref/forms/validation/#cleaning-和验证字段 - 依赖于每个其他
该文档说明了字段依赖关系如何完成,但我有一点点不同问题:
说我有一个有两个字段的模型:
类MyModel(models.Model):
field1 = models.CharField(max_length = 200)
field2 = models.CharField(max_length = 200)
并且说这两个字段之一是隐藏的,所以modelform看起来像这样:
class MyModelForm(forms.ModelForm):
class Meta:
...
widgets = {'field2':forms.HiddenImput()
现在,当用户填写ou表格,然后(在 clean_field1
)也填写 field2
。现在,我想报告 field2
发生的任何错误,作为关于 field1
的错误。这是因为目前用户不知道他做错了什么!
我试图做的是在ModelForm定义中:
def clean(self):
cleaning_data = super(MyModelForm,self).clean()
# $ b return clean_data
这是Django页面上呈现的内容。但是,问题是当执行 clean
方法时,字典 self.errors
是空的,所以我不知道该怎么办...
我不知道我的答案。但是,假设您正在使用 field1
数据,以生成 field2
值。您可以使用自定义方法生成它,并将其分配给 __ init __
方法中的字段。这将给你一个很好的方法来清理这两个领域。
class MyModelForm(forms.ModelForm):
def __init __(self,* args,** kwargs)
super(MyModelForm,self).__ init __(* args,** kwargs)
#现在可以使用field1数据生成field2数据
self.data [ 'field2'] = self.field [1] * 154220
class Meta:
widgets = {'field2':forms.HiddenInput()}
def clean_field1(self):
##这里您只能对field1进行验证。
##这样做不像field2不是现在的。
def clean_field2(self):
##这里只能对field2进行验证。
##这样做不像field1没有exisited。
def clean(self):
在这里你可以验证两个字段
raise ValidationError如果看到有什么问题
例如,如果你想确保field1!= field2
field1 = self.cleaned_data ['field1']
field2 = self.cleaned_data ['field2']
如果field1 == field2:
raise ValidationError(错误消息,不会告诉用户field2是错误的。)
返回clean_data
更新
如果您希望 clean
方法在特定字段中引发错误:
请注意,您的Form.clean()覆盖引起的任何错误都不会与任何字段特别相关联的
。他们进入一个特殊的
字段(称为全部),如果需要,您可以通过
non_field_errors()方法访问。如果要将错误
附加到表单中的特定字段,则需要调用add_error()。
所以从Django文档可以使用 add_error()
来做你想要实现的内容。
代码可以这样
def clean(self )
在这里你可以验证两个字段
raise ValidationError如果你看到任何错误的话
例如,如果你想确保field1!= field2
field1 = self.cleaned_data ['field1']
field2 = self.cleaned_data ['field2']
if field1 == field2:
#这会引发field1错误的错误。不是所有的形式
self.add_error(field1,你的错误消息)
返回clean_data
请注意,上述方法是Django 1.7及更高版本的新方法。
https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.add_error
I am looking at this piece of documentation:
The documentation explains how field dependency can be done, but I have a slightly different problem:
Say I have a model with two fields:
class MyModel(models.Model):
field1 = models.CharField(max_length=200)
field2 = models.CharField(max_length=200)
And say that one of the two fields is hidden, so the modelform looks like so:
class MyModelForm(forms.ModelForm):
class Meta:
...
widgets = {'field2': forms.HiddenImput()}
Now, when the user fills out the form, I then (on clean_field1
) also fill field2
. Now, I want to report any error that happens to field2
as an error about field1
. This is because at the moment, the user does not know what he did wrong!
What I tried to do was, in the ModelForm definition:
def clean(self):
cleaned_data = super(MyModelForm, self).clean()
# Do something here
return cleaned_data
As this is what is presented on the Django page. However, the problem is that when the clean
method is executed, the dictionary self.errors
is empty, so I don't know what to do...
I am not sure about my answer. However, let's assume that you are using the field1
data in order to generate field2
value. You can generate it using a custom method and assign it to the field in the __init__
method. Which will give you a good way to cleaning the two fields later.
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
# now lets generate field2 data using field1 data..
self.data['field2'] = self.field[1] * 154220
class Meta:
widgets = {'field2': forms.HiddenInput()}
def clean_field1(self):
## Here you can do validation for field1 only.
## Do it like field2 is not exisited.
def clean_field2(self):
## Here you can do validation for field2 only.
## Do it like field1 is not exisited.
def clean(self):
"""
In here you can validate the two fields
raise ValidationError if you see anything goes wrong.
for example if you want to make sure that field1 != field2
"""
field1 = self.cleaned_data['field1']
field2 = self.cleaned_data['field2']
if field1 == field2:
raise ValidationError("The error message that will not tell the user that field2 is wrong.")
return cleaned_data
Update
In case you want the clean
method to raise the error in a specific field:
Note that any errors raised by your Form.clean() override will not be associated with any field in particular. They go into a special "field" (called all), which you can access via the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you need to call add_error().
So from Django documentation you can use add_error()
to do what you want to achieve.
The code can be in this way
def clean(self):
"""
In here you can validate the two fields
raise ValidationError if you see anything goes wrong.
for example if you want to make sure that field1 != field2
"""
field1 = self.cleaned_data['field1']
field2 = self.cleaned_data['field2']
if field1 == field2:
# This will raise the error in field1 errors. not across all the form
self.add_error("field1", "Your Error Message")
return cleaned_data
Note that the above method is new with Django 1.7 and above.
https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.add_error
这篇关于同时验证两个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!