我想在自定义清理方法中验证许多字段。
到目前为止,我有这个:
class ProjectInfoForm(forms.Form):
module = forms.ModelChoiceField(
queryset=Module.objects.all(),
)
piece = forms.CharField(
widget=forms.Select(),
required=False,
)
span = forms.IntegerField(
max_value=100,
initial=48
)
max_span = forms.IntegerField(
max_value=100,
initial=0
)
def clean(self):
span = self.cleaned_data['span']
max_span = self.cleaned_data['max_span']
piece = self.cleaned_data.['piece']
# validate piece
try:
Piece.objects.get(pk=m)
except Piece.DoesNotExist:
raise forms.ValidationError(
'Illegal Piece selected!'
)
self._errors["piece"] = "Please enter a valid model"
# validate spans
if span > max_span:
raise forms.ValidationError(
'Span must be less than or equal to Maximum Span'
)
self._errors["span"] = "Please enter a valid span"
return self.cleaned_data
但是,如果两个子句都无效,这只会给我一条消息。如何获取所有无效消息。此外,我没有获得特定于字段的消息 - 如何包含要为特定字段显示的消息?
任何帮助都非常感激。
答案 0 :(得分:4)
存储错误,直到方法结束时才提高错误:
def clean(self):
span = self.cleaned_data['span']
max_span = self.cleaned_data['max_span']
piece = self.cleaned_data.['piece']
error_messages = []
# validate piece
try:
Piece.objects.get(pk=m)
except Piece.DoesNotExist:
error_messages.append('Illegal Piece selected')
self._errors["piece"] = "Please enter a valid model"
# validate spans
if span > max_span:
error_messages.append('Span must be less than or equal to Maximum Span')
self._errors["span"] = "Please enter a valid span"
if len(error_messages):
raise forms.ValidationError(' & '.join(error_messages))
return self.cleaned_data
答案 1 :(得分:1)
在这种情况下,您应该编写自定义clean_FIELDNAME方法。这样,在模板中使用{{form.errors}}时,以后可以显示以字段为中心的验证错误。 clean 方法o.t.h.用于验证跨越多个字段的逻辑。看看我上面发布的链接,你需要知道的有关验证django表单的所有内容。
答案 2 :(得分:0)
这是因为您使用的是raise
。
尝试用代码中的这两行替换它:
del self.cleaned_data['piece']
和
del self.cleaned_data['span']
答案 3 :(得分:0)
看来这在Django的更高版本中已更改(似乎在2.1及更高版本中有效):
from django import forms
class ContactForm(forms.Form):
# Everything as before.
...
def clean(self):
cleaned_data = super().clean()
cc_myself = cleaned_data.get("cc_myself")
subject = cleaned_data.get("subject")
if cc_myself and subject and "help" not in subject:
msg = "Must put 'help' in subject when cc'ing yourself."
self.add_error('cc_myself', msg)
self.add_error('subject', msg)
https://docs.djangoproject.com/en/dev/ref/forms/validation/#raising-multiple-errors有更多详细信息。