简体   繁体   English

从HTML标头中获取Django中正确的语言代码

[英]Get correct language code in Django from HTML header

I am trying to get language choices from HTML head ACCEPT-LANGUAGE header. 我正在尝试从HTML头ACCEPT-LANGUAGE标头中获得语言选择。 I have used parse_accept_lang_header() module for this. 我已经为此使用parse_accept_lang_header()模块。 But its returning me all the language code in small character. 但是它以小写字母的形式返回了我所有的语言代码。 like this [('pt-pt', 1.0), ('pt-br', 0.8), ('en-us', 0.5), ('en', 0.3)] But I want to get like first one in small character, second part in uppercase corrector. 像这样[('pt-pt', 1.0), ('pt-br', 0.8), ('en-us', 0.5), ('en', 0.3)]但我想成为第一个小字符,大写校正器的第二部分。 Like this [('pt-PT', 1.0), ('pt-BR', 0.8), ('en-US', 0.5), ('en', 0.3)] . 像这样[('pt-PT', 1.0), ('pt-BR', 0.8), ('en-US', 0.5), ('en', 0.3)] So how can I do so? 那我该怎么办呢?

My code is as following: 我的代码如下:

from django.utils.translation.trans_real import parse_accept_lang_header
header_locales =parse_accept_lang_header(
                                  request.META.get('HTTP_ACCEPT_LANGUAGE', None))

the header_locales return me the locale name in small charector. header_locales以小字符header_locales返回我的语言环境名称。

It would appear that django lower cases the language codes for you (thx dgel). django似乎为您提供了小写的语言代码(thx dgel)。 Is there a reason you need the uppercasized version? 您是否需要大写版本的原因? You could always split up the code and uppercase it yourself I guess. 我猜您总是可以自己拆分代码并将其大写。 Or you could duplicate the functionality of the parse_accept_lang_header code without the lowercase bit. 或者,您可以复制parse_accept_lang_header代码的功能而无需使用小写字母。 I'm not exactly sure what the use case is though. 我不确定用例是什么。

If you need to query your database, you could always use something like the following (from here and the original documenation ): 如果您需要查询数据库,则可以始终使用类似于以下内容(从此处原始文档 ):

MyClass.objects.filter(name__iexact=my_parameter)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM