Django's get_current_language strange behavior

非 Y 不嫁゛ 提交于 2020-01-06 04:30:45

问题


I want to set the lang attribute in my html tag to the current locale's language based on the language defined in my settings.py. I don't use the LocaleMiddleware and the user can not choose the language.

(I have different domain's for the same page. If someone want's to see the website in a different language, the user has to go to a different website )

settings.py

LANGUAGE_CODE = 'pl-PL'
USE_I18N      = True
USE_L10N      = True

LANGUAGES = [
    ('en', 'English'),
    ('de', 'German'),
    ('pl', 'Polish'),
    ('ru', 'Russian'),
    ('uk', 'Ukrainian'),
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'pipeline.middleware.MinifyHTMLMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
]

Django version

Django==2.0.9

Template

{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
{% get_language_info for LANGUAGE_CODE as lang %}

<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}">

Output

If I refresh the page without interacting I got sometimes:

  • pl
  • pl-pl
  • pl-PL

Why is that happening?


回答1:


You can try using {{ lang.code }} to get only pl part (it depends on language).


In this case Django gets user language preference from Accept-Language HTTP header, which usually contains several language codes, with priority.

It may contain multiple language-codes for one base language, depending on your system locale, browser settings, etc; i.e. pl-PL,pl-pl,pl;q=0.7 where q is priority.

Django parses header and sorts language codes based on priority. Since priority is the same for several codes - they will appear in different order in the result for each request and the first one will be used.



来源:https://stackoverflow.com/questions/59301978/djangos-get-current-language-strange-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!