5👍
Suggestion/answer:
I got some weird behaviour on that also! Because I was forgetting to add the ‘LocaleMiddleware’, double check if it is there, for illustration this is how my ‘MIDDLEWARE_CLASSES’ looks like:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
That Middleware is responsible for process your request and response, and add the language!
Also keep the code from ‘Sindri Guðmundsson’, which is changing right the lang!
EDIT
A little bit further! If we take a look at LocaleMiddleware:
def process_request(self, request):
language = translation.get_language_from_request(request)
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
So the question is! why Django needs that?! the answer: Because if you use {{ LANGUAGE_CODE }} it is reading from the REQUEST, so LANGUAGE_CODE must be in the request! otherwise ! it is not going to return it! so thats why this middleware exist!
Check it out the comment, in the actual source code of the middleware:
"""
This is a very simple middleware that parses a request
and decides what translation object to install in the current
thread context. This allows pages to be dynamically
translated to the language the user desires (if the language
is available, of course).
"""
Also check the docs: https://docs.djangoproject.com/en/1.3/topics/i18n/deployment/#how-django-discovers-language-preference
1👍
Check out set_language
in django.views.i18n
, line 33. You have to set the language code for the user in session:
if hasattr(request, 'session'):
request.session['django_language'] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
- [Django]-How do I override a get()/all()/filter() function in Django for lazy deletion?
- [Django]-Redirect to admin for login
- [Django]-How to assign GROUP to user from a registration form (for user) in Django?
0👍
Django CMS uses request.LANGUAGE_CODE to determine what language to use, if you don’t specifically asks for a certain language in your GET or POST parameters.
Django CMS uses a middleware, MultilingualURLMiddleware, to set request.LANGUAGE_CODE.
That middleware first looks for a language prefix in the url, then it looks for language a session key.
This means that if you want another language you can set it in the session variable once, but MultilingualURLMiddleware will still set request.LANGUAGE_CODE on every request.
- [Django]-Django: values_list(flat=True) but for multiple fields
- [Django]-Django: Filter objects by multiple key,value pairs of one foreign key model
- [Django]-A better django datetime filter at the admin panel