Custom error messages on Django’s auto generated modelforms

As I’ve written before, I’ve been adventuring into the world of Python lately, namely with PyGTK, Zope/Plone, and Django. Although I’m a huge newbie with these technologies, I’ve been picking up stuff pretty fast and I love Django and the speed at which I’m developing an application with it.

So after I started doing some stuff with newforms, I hit a wall. Newforms lets you generate a from from a model, and represents most of the model’s attributes in the form attributes format, except for one very important field: error_messages (or, if it does, is not yet documented).

After looking around for a while, and using a couple of tips from #django @ freenode, I came up with a solution for my problem, and since I haven’t found any exact reference to this problem anywhere else, here it is:


class myForm(ModelForm):
..def __init__(self, *args, **kwargs):
....super(myForm, self).__init__(*args, **kwargs)
....self.fields['field_name'].error_messages = {'required': "This field is required"}
..class Meta:
....model = myModel

(Sorry for the lack of indentation. Wordpress code tag doesn’t seem to like spaces.)

Maybe it would be a good idea in the future to specify a model attribute to contain those messages.

Related Posts:

2 Responses to “Custom error messages on Django’s auto generated modelforms”

  1. Niek Bouman Says:

    Nice post. Here a snippet which uses your idea, to change the ‘required’ message in all fields in the model:

    for field in self.fields.itervalues():
    ..if field.required:
    ….field.error_messages = {’required’: ‘my custom required message.’}

  2. Arnold Chan Says:

    It is very useful, saved me.
    thanks

Leave a Reply