Django provides a built-in internationalization (i18n) and localization (l10n) framework to make it easier to create web applications that support multiple languages. Here's a step-by-step guide on how to use Django's i18n and l10n features:
In your settings.py
file, make sure the following settings are configured:
python# settings.py
# Set the list of enabled languages for your project
LANGUAGES = [
('en', _('English')),
('es', _('Spanish')),
# Add more languages as needed
]
# Set the default language for your project
LANGUAGE_CODE = 'en'
# Enable i18n middleware
MIDDLEWARE = [
# ...
'django.middleware.locale.LocaleMiddleware',
# ...
]
In your Django code, use the _()
function to mark strings for translation. For example:
python# views.py
from django.shortcuts import render
from django.utils.translation import gettext as _
def my_view(request):
output = _("Hello, world!")
return render(request, 'my_template.html', {'output': output})
Run the following command to create the initial translation files:
bashpython manage.py makemessages -l es
This command generates a locale
directory with a subdirectory for each language specified in the LANGUAGES
setting. Inside each language directory, you'll find a .po
file that you can edit to provide translations.
Edit the .po
files in the locale
directory to provide translations for the marked strings. For example:
po# locale/es/LC_MESSAGES/django.po msgid "Hello, world!" msgstr "¡Hola, mundo!"
After you've provided translations, run the following command to compile the .po
files into binary .mo
files:
bashpython manage.py compilemessages
To activate a specific language in your views or templates, use the activate
function from django.utils.translation
. For example:
python# views.py
from django.utils.translation import activate
def set_language(request, language):
activate(language)
# Your view logic here
In your templates, use the {% trans %}
template tag to translate strings:
html<!-- my_template.html -->
<h1>{% trans "Hello, world!" %}</h1>
To allow users to switch between languages, you can use the {% get_current_language %}
template tag and provide language-specific URLs. For example:
html<!-- language_switcher.html -->
{% load i18n %}
{% get_current_language as current_language %}
{% for lang_code, lang_name in LANGUAGES %}
<a href="{% url 'set_language' lang_code %}?next={{ request.path }}" {% if lang_code == current_language %}class="selected"{% endif %}>
{{ lang_name }}
</a>
{% endfor %}
Make sure to define a URL pattern for the set_language
view in your urls.py
file.
With these steps, your Django application should be ready to support internationalization and localization. Users will be able to switch between languages, and your code will display translated strings based on the selected language.