Wednesday, February 1, 2012

Django language set in the database field applied on login

In one of my Django projects available only for logged in users I needed to set language setting in the database, so user can change the language setting in his profile.

Here comes a handy "user_logged_in" (Django >= 1.3) signal which lets us do things after user is logged in. In our case, we modify session and change the language.

My user_details.models.py:
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in
from django.utils.translation import ugettext_lazy as _
from django.db import models
from django.conf import settings

class UserProfile(models.Model):
    user = models.OneToOneField(User, blank=Flse)
    language = models.CharField(verbose_name=_(u"Interface Language"), 
                   max_length=4, choices=settings.LANGUAGES)

@receiver(user_logged_in)
def lang(sender, **kwargs):
    lang_code = kwargs['user'].userprofile.language
    kwargs['request'].session['django_language'] = lang_code


settings.py

gettext = lambda s: s

LANGUAGES = (
    ('pl',gettext('Polski')),
    ('en',gettext('English')),
    ('de',gettext('Deutsch')),
)

1 comment:

El Chorro said...

Thanks for this!

This works great for me until there is the 'next' parameter set.

My situation looks like this:
1. User has registered and has set his language 'en'.
2. User logs in with a web browser's language set to some other language.
3. If there is the 'next' parameter set it has the 'wrong' url language prefix set.

Do you know how to change the url language prefix in this case?