我正在使用Django 1.6.2并在ModelForms as mentioned in this question上添加了1.6版本的新元选项,表单上的错误并没有像我设置的那样显示。
我的代码:
的ModelForm
class UserRegisterForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password = forms.CharField(label='Password', widget=forms.PasswordInput)
class Meta:
model = MyUser
fields = ('email','first_name','last_name')
error_messages = {
'email': {
'invalid': u"Hai",
'required': u"Sup",
},
}
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserRegisterForm, self).save(commit=False)
user.set_password(self.cleaned_data["password"])
if commit:
user.save()
return user
模板
<div class="form-group emailgroup {% if form.email.errors %}has-error has-feedback{% endif %}">
<label for="emailfield">Dirección de correo electrónico</label>
<input type="email" class="form-control" id="emailfield" name="email" required placeholder="¿Cuál es tu dirección de correo electrónico?">
{% if form.email.errors %}<span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block">{{ form.email.errors }}</span>
{% endif %}
</div>
请注意模板中的以下行,其中我打印了字段的错误。
{% if form.email.errors %}<span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block">{{ form.email.errors }}</span>
{% endif %}
但我仍然收到预定义的错误消息。我做错了什么?
答案 0 :(得分:0)
将错误消息定义为类属性是常见的,而不是在内部Meta中。接下来是为您的电子邮件字段设置一个干净的方法,如果给定的电子邮件无效,将引发ValidationError:
error_messages = {
"invalid_email": "Email is invalid.",
}
def clean_email(self):
email = self.cleaned_data["email"]
# Check the content of email here
...
# If not valid raise ValidationException referencing the predefined error message
...
raise ValidationError(self.error_messages["invalid_email"], code="invalid_email",)
# If valid return value
return email