3

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?

doctaphred
  • 2,504
  • 1
  • 23
  • 26
  • Well, I asked this in hope of also [sharing the answer I'd finally found](http://meta.stackexchange.com/questions/17845/etiquette-for-answering-your-own-question), but I guess I have to wait 8 hours to do so. SO really is a pretty intimidating community to try to enter... – doctaphred Feb 12 '14 at 22:19
  • This looks like a duplicate of http://stackoverflow.com/a/3437158/1637351. – schillingt Feb 12 '14 at 23:55
  • It's similar, but I was specifically trying to find the new way in Django 1.6, which isn't mentioned in either that question or the answers. Maybe an answer there might have been a better choice, but at least now a Google search for "django 1.6 overriding modelform error messages" is actually helpful (since it links here). – doctaphred Feb 13 '14 at 18:40

1 Answers1

2

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?

Community
  • 1
  • 1
doctaphred
  • 2,504
  • 1
  • 23
  • 26