Sunday, November 22, 2009

Django auto language selection

I want user can select language he prefers. But I didn't found how to do it in Django easy. And I stopped on the following decision.

At first we need middleware which will detects language parameter in GET (name is in settings.LANGUAGE_COOKIE_NAME) and sets session's paramater `django_language`.
import settings

class LocaleDetectMiddleware(object):
    This middleware parse GET request and detects the language user chosen
    def process_request(self, request):
        if settings.LANGUAGE_COOKIE_NAME in request.GET:
            request.session['django_language'] = request.GET[settings.LANGUAGE_COOKIE_NAME]
Note, this middleware must be included in settings.INSTALLED_APPS before django.middleware.locale.LocaleMiddleware, because we use Django's standard locale detection routine.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.