Internationalization (often abbreviated as i18n) is the process of designing and developing an application in such a way that it can be easily adapted to different languages, regions, and cultures without requiring changes to the underlying codebase. This process ensures that your Django application can support multiple languages and locales efficiently.
Localization (l10n) is the actual adaptation of your application for a specific locale, which includes translating text, adjusting formatting (e.g., for dates and numbers), and possibly adapting the content to suit local customs. Localization works hand-in-hand with internationalization to create a fully localized experience for users in different regions.
In Django, i18n and l10n are supported out-of-the-box with features like translation strings, locale-aware formatting, and time zone handling.
To enable i18n and l10n in Django, you need to modify the settings.py
file.
settings.py
:USE_I18N = True # Enable internationalization
USE_L10N = True # Enable localization
USE_TZ = True # Enable time zone support
USE_I18N
enables support for translating strings in your application.USE_L10N
enables locale-aware formatting for numbers, dates, and time.USE_TZ
allows you to work with time zones correctly by storing times in UTC and converting them based on the user’s time zone.In settings.py
, you can define the languages your application will support. This is done using the LANGUAGES
setting.
LANGUAGES = [
('en', _('English')),
('fr', _('French')),
('de', _('German')),
('es', _('Spanish')),
]
Here, the LANGUAGES
setting is a list of tuples, where the first element is the language code (e.g., 'en'
, 'fr'
) and the second is the human-readable name for the language.
The default language code is 'en'
(English), but you can change it as needed:
LANGUAGE_CODE = 'en-us' # Default language for your site
You can modify this depending on the default language you want to serve.
To translate strings in Django, you use the gettext
(abbreviated _
) function. This is how you mark strings for translation:
from django.utils.translation import gettext as _
def greet_user(request):
message = _("Welcome to our website!")
return HttpResponse(message)
Here, "Welcome to our website!"
will be marked for translation.
makemessages
CommandAfter marking the strings for translation, run the makemessages
command to generate .po
files containing all the marked strings that need translation.
django-admin makemessages -l fr
This command creates a .po
file for the specified language (in this case, French) under the locale
directory.
.po
FilesIn the .po
file for each language, you’ll find the marked strings that need translation. Open the .po
file for the specific language, and provide the translated string.
Example for locale/fr/LC_MESSAGES/django.po
:
msgid "Welcome to our website!"
msgstr "Bienvenue sur notre site web !"
.po
FilesOnce the translations are added, you need to compile the .po
files into .mo
files, which Django uses to serve translations.
django-admin compilemessages
This will generate .mo
files in the appropriate locale
directories.
Django provides support for formatting dates, times, numbers, and currencies according to the locale settings.
Django uses the date
and time
template filters to format dates and times in a way that respects the current locale.
<p></p>
This will format the date_joined
field according to the locale. In the French locale, it will display something like “lundi, janvier 1, 2023.”
Django uses the floatformat
and localize
template filters to format numbers and currencies according to the locale.
<p></p>
In the French locale, it might display the price as €19.99
instead of $19.99
.
Django also provides support for time zone handling, which is important for applications serving users in multiple time zones.
Ensure that USE_TZ
is set to True
in settings.py
, as mentioned earlier. Additionally, you can set the default time zone:
TIME_ZONE = 'UTC' # Default time zone
Django automatically converts times to the user’s time zone, based on their preference. To set the user’s time zone, you can use django.utils.timezone.activate()
.
from django.utils import timezone
def my_view(request):
user_timezone = request.user.profile.timezone # Get user’s timezone from profile
timezone.activate(user_timezone)
return render(request, 'my_template.html')
Django allows you to use translation in templates as well.
{% endraw %}{% trans %}
Template TagThe {% endraw %}{% trans %}
tag is used in templates to mark text for translation.
<h1>{% endraw %}{% trans "Welcome to our website!" %}</h1>
Django will replace the string with the translated version, depending on the active language.
{% endraw %}{% blocktrans %}
Template TagFor more complex translations (e.g., text with variables), you can use {% endraw %}{% blocktrans %}
.
{% endraw %}{% blocktrans %}
Welcome, ! You have unread messages.
{% endraw %}{% endblocktrans %}
This allows translation of text that includes dynamic content like variables.
Django provides a way to change the language on a per-request basis, usually based on user preferences or browser settings.
You can change the language for the user by using the set_language
view provided by Django.
from django.utils.translation import activate
from django.shortcuts import redirect
def set_language(request):
user_language = request.GET.get('lang', 'en') # Get language from GET request
activate(user_language)
return redirect('index') # Redirect to the main page
This allows users to switch the language of the site dynamically.
Django provides a LocaleMiddleware
to handle automatic language selection based on the user’s request. It can choose a language based on the user’s browser settings or session data.
To enable it, add the middleware to MIDDLEWARE
in settings.py
:
MIDDLEWARE = [
'django.middleware.locale.LocaleMiddleware',
# other middleware...
]