以下是一個(gè) ValidationError
的例子:
from django.forms import ValidationError
v = ValidationError(
('Invalid value: %(value)s'), # 描述錯(cuò)誤信息
code='invalid', # 錯(cuò)誤的代號(hào)
params={'value': '42'}, # 要傳遞到錯(cuò)誤信息的參數(shù)
)
在 shell 中測(cè)試下:
>>> v.code
'invalid'
>>> v.messages
['Invalid value: 42']
我們?cè)谏弦黄幕A(chǔ)上用上 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 中測(cè)試下:
>>> 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']}