Django - Store the language of user in database

Viewed 1293

I am able to change the language of the user with built-in function of django

path('i18n/', include('django.conf.urls.i18n')),

In order to send email to user translated in his language, I want to know the activated language of the user.

How can I save the language of the in db?

Is there another way to know the language?

This is the session:

from django.utils import translation
request.session[translation.LANGUAGE_SESSION_KEY]
2 Answers

In your User model, you need to add a new field:

    interface_language = models.CharField(max_length=10, blank=True)

Then you need to create middleware like this:

from django.utils import translation

def language_middleware(get_response):
    def middleware(request):
        user = getattr(request, 'user', None)
        if user is not None and user.is_authenticated:
            translation.activate(user.interface_language)
        response = get_response(request)
        translation.deactivate()
        return response
    return middleware

The middleware needs to be added to your settings after django.contrib.auth.middleware.AuthenticationMiddleware:

MIDDLEWARE = [
    # ...
    'django.contrib.auth.middleware.AuthenticaitonMiddleware',
    'language_middleware',
    # ...
]

Alternatively, you can also use a Pypi package like django-user-language-middleware.

Saving the language preference to the database is an overhead that you can avoid using the tools that Django offers.

django.utils.translation.get_language, returns the language used in the current thread.

As documented in Django, this is an example:

from django.utils import translation

def welcome_translated(language):
    cur_language = translation.get_language()
    try:
        translation.activate(language)
        text = translation.gettext('welcome')
    finally:
        translation.activate(cur_language)
    return text

You can also use django.utils.translation.get_language_from_request to analyze the request to find what language the user wants the system to show, as explained in this answer.

Be sure, however, that you have correctly setup Django.

Marina Mele has written a tutorial you can check out for a second point of view.

Related