The world as a global village is comprising of different languages, ethnicity and gender. In this article I will introduce to you the concept of internalization with Django.
You will understand how an application can be built to reach a global audience using Djangoβs internalization by either.
- Manually changing the language code of your application
- Or using an extension to change language sessions.
Prerequisites:
- For getting the best out of this article, a basic understanding of Django is needed;
- How to setup a Django project and run an application
- Have gettext running on your machine, for linux run this command
sudo apt-get install gettext
- Install language switch, a firefox extension language switcher. If you have checked these prerequisites then lets proceed.
So I have successfully created a project config and an application app as shown in this file tree.
to run and compile your message create a folder called locale inside your app directory with mkdir app/locale
the locale/
directory we just created is where the magic happens, where our messages will be compiled.
If you have gettext
installed on your machine then import it with the following line of code from django.utils.translation import gettext as _
We can translate text either from the backend view (views.py) or from the frontend templating engine.
Translating from views
Translating from your template
We proceed further to generate a translated text file with django-admin makemessages -l es
if you open the locale folder, you'll see a django.po
file where the translation process takes place.
Make the following changes by changing your default language code in your settings.py
file from English to Spanish LANGUAGE_CODE = 'es'
and when you're done run application with the compile command
django-admin compilemessages
load your tags from the template with {% load i18n %}
as shown above.
To manually change the language from your settings.py
file
all you need to do is just change the language code from English to Spanish as previously shown above.
To change the language using an extension
If you have installed the language switcher extension, then include this line of code to your middleware in your settings.py
django.middleware.locale.LocalMiddleware
Please ensure to include this file after the sesion middleware precisely after
the common middleware as shown above.
If that is done, then toggle between language on your browser
I hope this was helpful, please give a follow if you found this helpful.
Top comments (0)