3

I need a way to determine the main language set in a browser. I found a really great solution for PHP but unfortunately I'm using Django / Python.

I think the information is within the HTTP_ACCEPT_LANGUAGE attribute of the HTTP Request.

Any ideas or ready-made functions for me?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ron
  • 22,128
  • 31
  • 108
  • 206

2 Answers2

2

This is a function that i used and that is my creation self.

def language(self):
        if 'HTTP_ACCEPT_LANGUAGE' in self._request.META:
            lang = self._request.META['HTTP_ACCEPT_LANGUAGE']
            return str(lang[:2])
        else:
            return 'en'

Just call it.

Community
  • 1
  • 1
developer
  • 21
  • 4
1

You are looking for the request.META dictionary:

print request.META['HTTP_ACCEPT_LANGUAGE']

The WebOb project, a lightweight web framework, includes a handy accept parser that you could reuse in this case:

from webob.acceptparse import Accept

language_accept = Accept(request.META['HTTP_ACCEPT_LANGUAGE'])
print language_accept.best_match(('en', 'de', 'fr'))
print 'en' in language_accept

Note that installing the WebOb package won't interfere with Django's functionality, we are just re-using a class from the package here that happens to be very useful.

A short demo is always more illustrative:

>>> header = 'en-us,en;q=0.5'
>>> from webob.acceptparse import Accept
>>> lang = Accept(header)
>>> 'en' in lang
True
>>> 'fr' in lang
False
>>> lang.best_match(('en', 'de', 'fr'))
'en'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • i know this but I need a way to detect the main language. Mostly the `HTTP_ACCEPT_LANGUAGE` is a string containing different languages etc – Ron Sep 04 '12 at 19:21
  • 1
    Just be aware that the client may not always pass `HTTP_ACCEPT_LANGUAGE` and even if it does, its value may not be correct. The most fool-proof method is and always will be to let the user explicitly pick their language. – Chris Pratt Sep 04 '12 at 19:21
  • its just a minor feature on my website. if i get the code, its nice. if not, i just use german or english... – Ron Sep 04 '12 at 19:28