0

I'm using Django 1.6.2 and the new meta options added in 1.6 version on ModelForms as mentioned in this question, the errors on the forms are not displaying like i set them to.

My code:

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

Template

<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>

Mind the following lines in the template where I print the errors of the field.

{% if form.email.errors %}<span class="glyphicon glyphicon-remove form-control-feedback"></span>
      <span class="help-block">{{ form.email.errors }}</span>
{% endif %}

But I still get the predefined error message. What am I doing wrong?

Community
  • 1
  • 1
Axel
  • 457
  • 9
  • 20
  • 1
    Could you please verify your indentation in this post? I'm not sure if that actually is your code (what would cause the problem) or only a copy/paste/formatting issue while creating the question. – timo.rieber Mar 07 '14 at 20:50
  • Thanks, I didn't notice it. It's in fact a copy-paste problem, it's indented properly in my code. – Axel Mar 07 '14 at 22:12
  • Thanks for clarifying. Another question: what do you mean with "I still get the predefined error message"? Where does it show? HTML5 validation at the input field or a field-related error message from server-side? – timo.rieber Mar 09 '14 at 16:27
  • We get a field-related error message. I'm forcing the form with an already existing email, and {{ form.email.errors }} prints a default message instead of u"Hai" – Axel Mar 09 '14 at 16:30

1 Answers1

0

It is common use to define error messages as class attributes, not within an inner Meta. Next is to have a clean method for your email field which will raise an ValidationError in case the given email is not valid:

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
timo.rieber
  • 3,727
  • 3
  • 32
  • 47
  • 4
    But this is confusing. The documentation doesn't say anything about having to call a custom clean_xyz() method. My understanding is that by simply defining a dictionary of error_messages in the Meta class, the default messages will be replaced with the newly defined ones. Am I missing something? – pkout May 21 '14 at 04:45