Internationalization in Django Apps Explained
Q: How do you handle internationalization and localization in a Django app? Can you provide an example of how you would translate your app to another language?
- Django
- Mid level question
Explore all the latest Django interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Django interview for FREE!
In Django, internationalization (i18n) and localization
(l10n) can be easily handled using Django's built-in i18n framework. This
framework provides a set of tools for translating text strings and formatting
dates, times, and numbers for different locales.
Here's an example of how you would translate your app to
another language using Django's i18n framework:
- Enable
i18n in your Django project by adding 'django.middleware.locale.LocaleMiddleware'
to the MIDDLEWARE setting in settings.py.
- Define
the languages you want to support in the LANGUAGES setting in settings.py.
For example:
LANGUAGES = [ ('en', 'English'), ('es', 'Spanish'), ('fr', 'French'), ]
- Mark
all the text strings in your templates and Python code that need to be
translated using the gettext function or its shortcut _(...).
For example:
from django.utils.translation import gettext as _ def my_view(request): output = _("Welcome to my site.") return HttpResponse(output)
<h1>{% trans "Welcome to my site." %}</h1>
- Create
translation files for each language you want to support using the makemessages
and compilemessages management commands. For example, to create
translation files for Spanish:
python manage.py makemessages -l es
This command will scan your codebase for all the text
strings marked for translation and create a django.po file in the locale/es/LC_MESSAGES
directory. This file can be edited manually or with a translation management
tool like Poedit.
After you've translated the strings, run the following
command to compile the translations:
python manage.py compilemessages
- Set
the language preference in the user's session or through the URL using the
set_language view provided by Django. For example, you could add
the following URL pattern to your URL configuration:
from django.conf.urls.i18n import i18n_patterns from django.views.i18n import set_language urlpatterns = [ # ... ] urlpatterns += i18n_patterns( path('set_language/', set_language, name='set_language'), # ... )
This URL pattern maps the /set_language/ URL to
Django's set_language view, which sets the user's language preference in
their session.
With these steps, your app should be fully translated to the
supported languages, and users should be able to switch between languages using
the language switcher provided by Django.


