Create Custom Error Messages with Model Forms

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?

Leave a Comment