我写了一个注册的 表单和 视图函数。其中有error_messages这个属性,用来提示用户:“改用户名已存在”、“两次密码输入不匹配”这两个信息。但是我不知道该怎么使用 。求大神请教~
表单代码(仅包含重要代码,其余代码不在里面):
class RegisterForm(forms.ModelForm):
error_messages = {
'duplicate_username': "username already existed",
'password_mismatch': "passwords didn't match",
}
username = forms.CharField(
label=u"用户名",
max_length=30,
)
password1 = forms.CharField(
label= u'密码',
widget=forms.PasswordInput,
)
password2 = forms.CharField(
label= u'确认密码',
widget=forms.PasswordInput,
help_text=u"Enter the same password as above, for verification.",
)
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data['username']
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(
self.error_messages['duplicate_username'],
code='duplicate_username',
)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
视图函数代码:
def register(request):
register_form = RegisterForm(request.POST or None)
if request.method == 'POST':
if register_form.is_valid():
register_form.save()
return HttpResponseRedirect(reverse('loginapp.views.login',kwargs={}))
return render_to_response('register.html',RequestContext(request,{'register_form': register_form,}))