How to translate a website based on Django ?

Published: February 10, 2021

Tags: Django; Translation; gettext; Protection Status

A quick guide on how to translate a website based on Django:

Edit the file

Let's assume that we want our django website available in English and French. First step, let's edit the file by adding the following lines:

from django.utils.translation import ugettext_lazy as _



USE_I18N = True

USE_L10N = True

USE_TZ = True

    ('en-us', _('English')),
    ('fr', _('French')),

    os.path.join(BASE_DIR, 'locale'),

here by default the site is in english (LANGUAGE_CODE = 'en-us').

Create locale folder

Next step lets create a folder named "locale" at the root of the django project:

mkdir locale

so it should look like this:


Edit template files

Next, in all templates files (for example home.html) change the text that you want to be translated to

{% trans 'text' %}

for examples:

{% trans 'Hello everyone !' %}


{% trans 'search' %}

Edit the file

In the file add the following line:

 from django.utils.translation import gettext

and then change all text that you want to be translated to

text = gettext("text")

for example with an error message:

err_msg = gettext("Oups somehting went wrong")

Create translation files

Now we can start to create the transaltion files that will be stored in the local folder than we created just above. For that it is necesary to install gettext. The installation depends on your current system, for example on mac (see How to install gettext on MacOS X) with homebrew:

brew unlink gettext && brew link --force gettext

To check where gettext has been installed (for example /usr/local/Cellar/gettext/0.21):

brew info gettext

then enter:


to avoid the following error when you wiill try to compile the messages (see django i18n doesn't work in mac):

CommandError: errors happened while running msguniq
msguniq: Cannot convert from "ASCII" to "UTF-8". msguniq relies on iconv(). This version was built without iconv().

Now in your terminal go to the root of your project:


and enter the following commands : makemessages -l fr
django-admin compilemessages

It should then create the files in the folder locale:


Edit the .po file

Then edit the .po file to translate the text.

Note: to edit the .po file there are some text editor such as poedit.

Change the language

Two options (set language within a django view, Explicitly setting the active language, Can't change language in django):

(1) in the file change:




(2) in add the following line

from django.utils import translation

you can now change from french

language = 'fr' 

or english in a django view

language = 'en-us' 

Note: can be useful if you want to let the visitor pick up their preferred language. Create a link:


and in

if 'language' in request.GET and request.GET['language']:
    language = request.GET['language']
    if language in ['fr','en']:
        if language == 'fr': 
        if language == 'en':