5👍
I tried to simulate your environment with these steps:
$ cd ~
$ python3 -m venv ~/venvs/mysite
$ source ~/venvs/mysite/bin/activate
$ pip install django==2.0.8
$ django-admin startproject mysite
Then I updated the generate code as in your example:
-
mysite/settings.py
... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ...
-
mysite/urls.py
from django.contrib import admin from django.urls import path from django.views.generic.base import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name='base.html'), name='home'), path('admin/', admin.site.urls), ]
-
templates/base.html
{% load i18n %} {% get_current_language as LANGUAGE_CODE %} <!DOCTYPE html> <html lang="{{ LANGUAGE_CODE }}"> <body> <pre>LANGUAGE_CODE = {{ LANGUAGE_CODE }}</pre> <body> </html>
With the Django generated code and my few above updates I can see different language code if I switch the language of my browser visiting http://localhost:8000/ after starting it with:
$ python manage.py runserver
Try my steps on your local environment and check if it works, and then compare your project to the code above.
Update
Try to use diffsettings to see “differences between the current settings file and Django’s default settings”.
0👍
Had the same problem. In my case, the function was called async and always returned the default language.
SOLUTION: pass language from ‘main’ context.
Code like in this example:
def get_context_data( self, **kwargs ):
context = super().get_context_data(**kwargs)
lng_code = get_language() # -> 'de'
@sync_to_async
def get_data():
context['data1'] = Model1.objects.filter(language==get_language()) # get_language() -> 'en'
@sync_to_async
def get_data2():
...
@sync_to_async
def get_data3():
...
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(
asyncio.gather(
get_data1(),
get_data2(),
get_data3()
))
loop.close()
Source:stackexchange.com