0

I need django i18n to work like this: site.com/lang/ set the session language to lang, writes it to the cookie and redirects user to site.com. If it's a first-time visitor and prefix is not specified, default lang is shown.

Sorry for such a basic question,example of urls.py and middlewares maybe would be extremely appreciated.

1 Answers1

0

Django comes with a pretty similar solution to what you are trying to do. It's called The set_language Redirect view. The difference is that it expects the language as a POST parameter. You might want to consider using this versus a custom solution.

If that's not what you're looking for, you could write your own Redirect View, that would set the language to lang and redirect to site.com

class SetLanguageView(RedirectView):
    url = reverse('home')

    def get(self, request, *args, **kwargs):
        response = super(self, SetLanguageView).get(request, *args, **kwargs)
        lang = kwargs.get('lang')
        if lang:
            # To set the language for this session
            request.session[settings.LANGUAGE_SESSION_KEY] = lang
            # To set it as a cookie
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang,
                                max_age=settings.LANGUAGE_COOKIE_AGE,
                                path=settings.LANGUAGE_COOKIE_PATH,
                                domain=settings.LANGUAGE_COOKIE_DOMAIN)
        return response

And in urls.py you would have something like

urlpatterns = patterns('',
    url(r'^(?P<lang>\w+)/$', RedirectView.as_view(), name='lang_redirect'),
zanderle
  • 815
  • 5
  • 15