Building globally with Django internalization

Building globally with Django internalization

how to use Django internalization for your project

·

2 min read

The world as a global village is comprising of different language, 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.

  1. Manually changing the language code of your application
  2. Or using an extension to change language sessions.

Prerequisites:

  1. 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
  2. Have gettext running on your machine, for linux run this command sudo apt-get install gettext
  3. 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. Image description

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

Image description

Translating from your template

Image description

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. Image description Make the following changes by changing your default language code in your settings.py file from English to Spanish LANGUAGE_CODE = 'es' Image description

and when you're done run application with the compile command django-admin compilemessages load your tags from the template with {% load i18n %}.

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 django.middleware.locale.LocalMiddleware to your middleware in your settings.py Image description

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 Image description

I hope this was helpful, please give a follow if you found this helpful.