Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Custom Error Messages with Model Forms

People also ask

What is custom error message?

Custom error pages enable you to customize the pages that display when an error occurs. This makes your website appear more professional and also prevents visitors from leaving your site.

What is the difference between forms and model forms in Django?

The main difference between the two is that in forms that are created from forms. ModelForm , we have to declare which model will be used to create our form. In our Article Form above we have this line " model = models. Article " which basically means we are going to use Article model to create our form.

How do I display validation error in Django?

To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.


New in Django 1.6:

ModelForm accepts several new Meta options.

  • Fields included in the localized_fields list will be localized (by setting localize on the form field).
  • The labels, help_texts and error_messages options may be used to customize the default fields, see Overriding the default fields for details.

From that:

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        labels = {
            'name': _('Writer'),
        }
        help_texts = {
            'name': _('Some useful help text.'),
        }
        error_messages = {
            'name': {
                'max_length': _("This writer's name is too long."),
            },
        }

Related: Django's ModelForm - where is the list of Meta options?


For simple cases, you can specify custom error messages

class AuthorForm(forms.ModelForm):
    first_name = forms.CharField(error_messages={'required': 'Please let us know what to call you!'})
    class Meta:
        model = Author

Another easy way of doing this is just override it in init.

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author

    def __init__(self, *args, **kwargs):
        super(AuthorForm, self).__init__(*args, **kwargs)

        # add custom error messages
        self.fields['name'].error_messages.update({
            'required': 'Please let us know what to call you!',
        })

I have wondered about this many times as well. That's why I finally wrote a small extension to the ModelForm class, which allows me to set arbitrary field attributes - including the error messages - via the Meta class. The code and explanation can be found here: http://blog.brendel.com/2012/01/django-modelforms-setting-any-field.html

You will be able to do things like this:

class AuthorForm(ExtendedMetaModelForm):
    class Meta:
        model = Author
        field_args = {
            "first_name" : {
                "error_messages" : {
                    "required" : "Please let us know what to call you!"
                }
            }
        }

I think that's what you are looking for, right?


the easyest way is to override the clean method:

class AuthorForm(forms.ModelForm):
   class Meta:
      model = Author
   def clean(self):
      if self.cleaned_data.get('name')=="":
         raise forms.ValidationError('No name!')
      return self.cleaned_data