[Django]-Changing the field name django uses when display form error messages

4๐Ÿ‘

โœ…

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/

Leave a comment