The documentation of translation in Django is pretty well done, but quite long. If you want to setup it up easily, here are the steps.
Translation Setup
Make sure you have gettext installed on your machine. I wrote an article about the OSX specificities.
1 2 3 4 5 6 |
# Ubuntu $ sudo apt-get install gettext # OSX $ brew install gettext $ brew link gettext --force |
Create a locale folder inside your main project folder
1 |
$ mkdir mysite/locale |
Django will create subfolders in the locale folder for each language you want to support.
Make sure you include the middleware class in your settings.py file, create or modify the languages settings and set the LOCALE_PATH variable :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
MIDDLEWARE_CLASSES = ( ... 'django.middleware.locale.LocaleMiddleware', ... ) LANGUAGES = ( ## Customize this ('en', gettext('en')), ('fr', gettext('fr')), ) LOCALE_PATHS = ( 'locale', ) |
Depending on your project structure, you might need to change the locale path to suit your needs. It’s often the cause of the translations not working !
Translation in .py files
We create an alias to it’s easier to use and I think it makes it more readable.
We can add a special comment which will be displayed in the translation file. It can be useful for your translators.
1 2 3 4 5 6 7 |
from django.utils.translation import ugettext as _ from django.http import HttpResponse def my_view(request): # Translators: This message appears on the home page only output = _("Welcome to my site.") return HttpResponse(output) |
There are a lot of other possibilities. Please read the documentation.
Translation in templates
We need to indicate that we’re using translation, so put that code somewhere near the top of your template.
1 |
{% load i18n %} |
Then it’s pretty easy
1 2 |
<title>{% trans "This is the title." %}</title> <title>{% trans myvar %}</title> |
Again, a lot of options and other methods are available, please read the doc.
Create the language files
Fortunately, Django is doing that for us ! Let’s create the french file :
1 |
$ django-admin makemessages -l fr |
Django will create the file in mysite/locale/fr/LC_MESSAGES/django.po
It’ll look like this :
1 2 3 |
#: auth/views.py:84 msgid "Username/password combination invalid" msgstr "" |
You simply have to fill out msgstr with the translated phrase.
If you add new phrases in your code, just run
1 |
$ django-admin makemessages -a |
It’ll update all the languages.
Now, the last step : compiling the files into .mo files (binary files optimized for gettext)
1 |
$ django-admin compilemessages |
And you’re pretty much done. It’s really awesome to see how easy it is.
Quick guide about #Django translation https://t.co/608lya99T3 #Python #web #dev