DEV Community

Cover image for Django Internationalization Tutorial-4
ajitdhulam for Python Discipline @EPAM India

Posted on • Edited on

Django Internationalization Tutorial-4


Dynamically Change language, based on user choice.

In the last post, demonstrated how to translate Django templates and JavaScript code. However, even though there are several ways to control how Django utilizes translations, we have so far utilized the settings to establish an application-wide language. In this last post, I will teach you how to configure Django to utilize a user-defined language.

Setting different languages by user local
Django has a flexible methodology for determining which language to use for translations. In this part, I will teach you how to use translations based on the browser's supported language. To begin, open the settings file (languages/ settings.py) and ensure that English is selected as the default language:

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'
Enter fullscreen mode Exit fullscreen mode

Now, we must tell Django which languages we have available for translations. Add the LANGUAGES list to your settings file

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

from django.utils.translation import ugettext_lazy as _

LANGUAGES = (
    ('en-us', _('English')),
    ('pt-pt', _('Portuguese')),
)

LANGUAGE_CODE = 'en-us'
Enter fullscreen mode Exit fullscreen mode

Finally, we must add the LocaleMiddleware to our list of middleware classes:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',  # add this extra
    'django.middleware.common.CommonMiddleware',
    ...
    ...
]
Enter fullscreen mode Exit fullscreen mode

Start the server, and Django should now be able to return your translations. If you make any modifications to the messages, remember to compile them.

Selecting User language from list on web
Django is to allow the user to select from a list. It uses the set_language redirect view.
First, open languages/urls.py and include the set_language view:

from django.views.i18n import JavaScriptCatalog
from django.urls import path, include

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
    path('i18n/', include('django.conf.urls.i18n')),
]

Enter fullscreen mode Exit fullscreen mode

Now, open the template file at templates/languages/index.html and include the form to select the language:

{% load i18n %}

<h1>{% trans 'Hello' %}</h1>
<p>{% trans 'Welcome to my site.' %}</p>

<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
    <input name="next" type="hidden" value="{{ redirect_to }}">
    <select name="language">
        {% get_current_language as LANGUAGE_CODE %}
        {% get_available_languages as LANGUAGES %}
        {% get_language_info_list for LANGUAGES as languages %}
        {% for language in languages %}
            <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
                {{ language.name_local }} ({{ language.code }})
            </option>
        {% endfor %}
    </select>
    <input type="submit" value="Go">
</form>
Enter fullscreen mode Exit fullscreen mode

The form displays a list of languages before sending a POST request to the set language view with the language selected. Finally, open languages/views.py and ensure that render is used to render the template rather than render to response, as the latter fails to include the csrf token:

from django.shortcuts import render

def index(request):
    return render(request, 'languages/index.html')
Enter fullscreen mode Exit fullscreen mode

Finally, because this technique makes use of the session variable, you may need to use python3 manage.py migrate to construct the database tables.

Image description

and finally the whole web page translate demo based on user choosen language.

Image description

References:
https://lokalise.com/blog/django-i18n-beginners-guide/
http://www.marinamele.com/taskbuster-django-tutorial/internationalization-localization-languages-time-zones
https://www.pycorners.com/
https://phrase.com/blog/posts/quick-guide-django-i18n/
https://www.pycorners.com/storie/6/2020/12/2/django-web-page-translation
https://www.youtube.com/watch?v=z_p8WxFGV5A&ab_channel=VeryAcademy
https://www.youtube.com/watch?v=AlJ8cGbk8ps&t=2s&ab_channel=PrettyPrinted

Disclaimer: This is a personal [blog, post, statement, opinion]. The views and opinions expressed here are only those of the author and do not represent those of any organization or any individual with whom the author may be associated, professionally or personally.

Top comments (0)