以下是一个 ValidationError
的例子:
from django.forms import ValidationError
v = ValidationError(
('Invalid value: %(value)s'), # 描述错误信息
code='invalid', # 错误的代号
params={'value': '42'}, # 要传递到错误信息的参数
)
在 shell 中测试下:
>>> v.code
'invalid'
>>> v.messages
['Invalid value: 42']
我们在上一篇的基础上用上 ValidationError
:
from django import forms
class UserRegisterForm(forms.Form):
user_name = forms.CharField()
password1 = forms.CharField()
password2 = forms.CharField()
def clean(self):
cleaned_data = super(UserRegisterForm, self).clean()
password1 = cleaned_data.get("password1")
password2 = cleaned_data.get("password2")
if password1 != password2:
raise forms.ValidationError(
('两次密码不一致。 Invalid value: %(value)s'),
code='invalid',
params={'value': password2},
)
在 shell 中测试下:
>>> from myApp.forms import UserRegisterForm
>>> f = UserRegisterForm({'name':'abc', 'password1': '12345', 'password2': '1234'})
>>> f.errors
{'user_name': ['This field is required.'], '__all__': ['两次密码不一致。 Invalid value: 1234']}