Question

Okay so I have a form and then in the template, I have this code:

{% if form.errors %}
    { form.errors %}
{% endif %}

Now, suppose I have a username field in my form which is required and I purposely do not fill it out. It would say

username
    -This field is required

How do I change the word "username" which it displays when telling what field the error message is for? I'm guessing it is taking the name from the Model I created because in the model (which I then made a form of) I had written

username = models.CharField(max_length=10)
first_name = models.CharField(max_length=20)

As you can see, if there is an error with the first_name field, it django would display

first_name
    - *error message*

How would I make it display "First Name" instead of "first_name"?

Was it helpful?

Solution

If you want to put some custom messages to your erros you may want to modify the clean method of your formfields.

For example:

class Form(forms.ModelForm):
    class Meta:
        model = User #Assuming User is the name of your model
        fields = ['username','first_name']

    def clean_first_name(self):
        if condition: # A condition that must raise an error
            raise forms.ValidationError(u'Your Custom Validation Error goes here.')
        return self.cleaned_data['first_name']

But if you just want to change the name that appears in a default error message you can put a verbose name in your fields, just like:

username = models.CharField(max_length=10, verbose_name="Username")
first_name = models.CharField(max_length=20, verbose_name="First Name")

or implicit:

username = models.CharField("Username", max_length=10)
first_name = models.CharField("First Name",max_length=20)

To see more about django form and field validation: https://docs.djangoproject.com/en/1.5/ref/forms/validation/#form-and-field-validation

About Override default Form error messages: Django override default form error messages

and

http://davedash.com/2008/11/28/custom-error-messages-for-django-forms/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top