本文介绍了Django的get_current_language奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据我的settings.py中定义的语言,将html标记中的lang属性设置为当前语言环境的语言.我不使用LocaleMiddleware,用户无法选择语言.

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版本

Django == 2.0.9

Django==2.0.9

模板

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

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

输出

如果我在没有交互的情况下刷新页面,有时会得到:

If I refresh the page without interacting I got sometimes:

  • pl
  • pl-pl
  • pl-PL

为什么会这样?

推荐答案

您可以尝试使用{{ lang.code }}仅获取pl部分(取决于语言).

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

在这种情况下,Django从 Accept-Language (HTTP语言)标头获取用户语言首选项,该标头通常包含多个具有优先级的语言代码.

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

它可能包含一种基本语言的多种语言代码,具体取决于您的系统区域设置,浏览器设置等;即 pl-PL,pl-pl,pl; q = 0.7 ,其中 q 是优先级.

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解析标头并根据优先级对语言代码进行排序.由于多个代码的优先级相同-每个请求的结果将以不同的顺序出现,并且将使用第一个.

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.

这篇关于Django的get_current_language奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 21:32