1

I am trying to get language choices from HTML head ACCEPT-LANGUAGE header. I have used parse_accept_lang_header() module for this. 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. Like this [('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.

safwan
  • 383
  • 2
  • 6
  • 1
    If it is only lower-case because of `parse_accept_lang_header`, you might consider just copying the source of `parse_accept_lang_header` ([it's pretty straightforward](https://github.com/django/django/blob/1.8/django/utils/translation/trans_real.py#L731)) into your app and modifying it to not change to lower case. Probably your fastest path. – dgel Jul 07 '15 at 22:07

1 Answers1

1

It would appear that django lower cases the language codes for you (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. 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)
Community
  • 1
  • 1
CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
  • 1
    [django does muck with it](https://github.com/django/django/blob/1.8/django/utils/translation/trans_real.py#L739) – dgel Jul 07 '15 at 21:55
  • @dgel Oh, because he's calling parse_accept_lang_header. Durp, ofc. I thought he was saying the string inside the request.META.get was lower case. – CrazyCasta Jul 07 '15 at 22:02
  • I need Uppercase version to show the language code to match with my database. In database, its in lowercase and uppercase mixed version! :/ – safwan Jul 07 '15 at 22:02
  • @safwan You could always just do a case insensitive query, see my edit. – CrazyCasta Jul 07 '15 at 22:06
  • @CrazyCasta Yap, I know about this. But I am finding if its possible to make the header code uppercase. So I can show it to the user also. Thanks a lot for this. – safwan Jul 07 '15 at 22:28
  • 1
    Ah, well then your only choices are to post process the results of `parse_accept_lang_header` or just copy/paste and tweak that function. – CrazyCasta Jul 07 '15 at 22:38