Django Internationalization: Translation
Introduction
Internationalization (i18n) is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Django provides robust support for translating text within your web application, making it easier to reach a global audience. This tutorial will guide you through the steps to add translation support to your Django project.
Setting Up the Project
To get started with translations in Django, make sure that your project is set up correctly. Ensure that the USE_I18N
setting is enabled in your settings.py
file:
USE_I18N = True
Also, set the LANGUAGE_CODE
to your default language, for example:
LANGUAGE_CODE = 'en-us'
Marking Strings for Translation
To mark strings for translation in your Django app, use the gettext
function or its alias _
. Here's an example of marking a string for translation in a view:
from django.utils.translation import gettext as _
def my_view(request):
output = _("Welcome to my site.")
return HttpResponse(output)
Creating Translation Files
Once your strings are marked for translation, you need to create message files. Run the following command to extract the strings marked for translation:
django-admin makemessages -l es
This command will create a file named django.po
in the locale/es/LC_MESSAGES/
directory. Open this file and provide the translations for each string.
Compiling Translations
After providing translations, you need to compile them so that Django can use them. Run the following command to compile the translations:
django-admin compilemessages
Using Translations in Templates
To use translations in Django templates, load the i18n
tags and use the trans
template tag:
{% load i18n %}
<h1>{% trans "Welcome to my site." %}</h1>
Switching Languages
To switch languages, you can use Django's built-in set_language
view. You can include a language switcher form in your templates:
<form action="/i18n/setlang/" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
<select name="language">
<option value="en">English</option>
<option value="es">Español</option>
</select>
<input type="submit" value="Go" />
</form>
Conclusion
By following this tutorial, you have learned how to set up internationalization in your Django project, mark strings for translation, create and compile translation files, and use translations in your templates. With these tools, you can make your Django application accessible to a global audience.