doctaphred
doctaphred

Reputation: 2644

Overriding ModelForm field error messages in Django 1.6

hjwp's wonderful Test-Driven Development with Python book demonstrates overriding default ModelForm field error messages in chapter 11:

from django import forms

from lists.models import Item

class ItemForm(forms.models.ModelForm):

    class Meta:
        [...]


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        empty_error = "You can't have an empty list item"
        self.fields['text'].error_messages['required'] = empty_error

But then proclaims (it's a work in progress)...

Django 1.6 has a simpler way of overriding field error messages. I haven’t had time to implement it yet, but you should feel free to look it up and use it!

This has proven a surprisingly difficult topic to look up, and I hope to save someone else the time. What is the simpler way to accomplish it?

Upvotes: 3

Views: 1427

Answers (1)

doctaphred
doctaphred

Reputation: 2644

From the Django 1.6 release notes:

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?

Upvotes: 2

Related Questions