Brendel Consulting logo

Brendel Consulting

composing beautiful software solutions

Sep 23, 2010

How to customize Django's default messages

Ever tried to customize a message produced by one of Django's generic views or standard field validators? This is a problem I run into pretty often.

Custom validator messages

In some cases Django offers you some pretty straight forward options, such as specifying an error_messages dictionary as argument to a field validation:

email = forms.EmailField(label = "Email address",
                         error_messages = {'required' : "Please enter an email address.",
                                           'invalid'  : "Malformed address. Please correct."})

Hard-coded messages

Sometimes, however, easy options like this do not exist. For example, take the generic password_reset view offered by django.contrib.auth. If you look at the source code for this view function, you find that by default it uses PasswordResetForm - also contained in the same package - as its standard form. The problem is that this form has a few hard-coded messages in it, so there is no obvious way to modify those if you just want to continue to use the standard views and forms.

The password_reset view gives you the option of specifying your own form - with the messages you want - by setting the password_reset_form parameter. For example, by doing this in your file:

(r'^password/reset/$', 'django.contrib.auth.views.password_reset',
                       { 'template_name' : 'my_pw_reset_form.html',
                         'email_template_name' : 'my_pw_reset.txt',
                         'password_resset_form' : MyForm }),

I don't know about you, but the thought of essentially copying an entire form implementation just so that I can change some message text is not very attractive to me. Some of these forms consist of more than just field definitions and I don't want to be in the business of creating and maintaining 'mini-forks' of various Django components.

A better way

It seems that there should be a better way and I think there is: Let's use Django's built-in translation system for the task.

Django's translation is capable of taking any specially marked text in any of your files (including Python source code) and looking up a translated string for it, based on the locale of your site or user. For example, in your Python source code, you could write this:

from django.utils.translation import ugettext_lazy as _
msg = _("Here is some text")

The _() function here is the special marker and also performs the on-the-fly translation at runtime. In templates you use the {% trans ... %} template tag. You can read more about it here.

Fortunately, the hard-coded messages in the standard Django views and templates are prepared for translation. Therefore, the idea now is simple: Even if otherwise you are not interested in translation and internationalization, you simply use this mechanism to provide 'custom translations' for the selected messages you are interested in!

In my file, the LANGUAGE_CODE setting is 'en-us'. You may have a different setting, but that doesn't matter. While in your settings file, make sure that USE_I18N is set to True and that you include django.contrib.messages.middleware.MessageMiddleware in your MIDDLEWARE_CLASSES.

In your project directory, make sure you have a 'locale' directory (create it if it's missing) and then run this command:

% makemessages -l en

This utility examines all your files for strings that are marked for translation. In this case, I am asking it to create translation files for 'en' (English), but you can define whatever was specified in your LANGUAGE_CODE setting.

Have a look at the locale/[local-id]/LC_MESSAGES/django.po file that was created ([locale-id] in my case is 'en', it may be different for you). If you don't have any of your own messages marked for translation, this file will be mostly empty. A .po file contains messages - that are recognized at runtime - and their translations that need to be applied. It's quite straight forward.

Now with an editor open the standard .po file for your locale that comes with a Django install. Django may be in your Python install's site-packages directory. The path therefore should be something like this:


In that file, search for the message you would like to customize. For our password-reset example, I don't like the standard message it displays when the email address cannot be found. In the standard django.po we find this message represented like this:

#: contrib/auth/
msgid ""
"That e-mail address doesn't have an associated user account. Are you sure "
"you've registered?"
msgstr ""

This shows us that currently no translation is provided for this message (msgstr is empty). If you don't have an English language locale then you probably already see a translation specified right here.

Now instead of editing the message in the standard .po file that comes with Django - I don't like editing standard files like that - copy these lines into your own django.po file in your project directory. Use msgstr to define whatever text you want to be displayed instead. Single line messages can be written right into the two quotes behind msgstr, multi-line messages are written the way you see it done for msgid. In our example, I just say:

msgstr "Unknown email. Are you sure you have registered with that address?"

So, you now have provided a second translation for your default locale. Since Django looks first in your project's directory for translations of individual messages, it finds this translation before it falls back on the default provided by Django itself.

% compilemessages

Now you can restart your server and you should see your customized default message in action!


An annoying habit of the makemessages utility is that it comments out your custom messages out of your .po file every time it is run. The utility is pretty good in not losing any changes you make in that file, but every translation you add for which makemessages does not find the text in your project's files is going to be commented out. And since you are providing a translation for a standard Django message - and Django most likely is not part of your project - this will apply to the custom messages we are talking about here.

You could just manually remove all the comment identifiers ("#~ "). However, since I'm lazy, I wrote a little script, which not only removes those comments for me, but also calls compilemessages. Just create a file called in your project directory with the following content:


echo "### Translating all messages..." makemessages -a
echo "### Removing commented-out manual messages..."
find locale -name 'django.po' -exec sed s/^\#\~\ // -i {} \;
echo "### Compiling messages..." compilemessages
echo "### Done!"

Once you give execute permissions to that file, you can get all your project's messages discovered and compiled, while also retaining any of your customizations for Django's default messages, simply by running this command.

Pretty convenient, isn't it?

If you liked this little article, please consider following me on Twitter.

Labels: , , , , , ,



Post a Comment

Subscribe to Post Comments [Atom]

<< Home