Custom error messages on Django’s auto generated modelforms

March 26th, 2008

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.