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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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'

3 Comments

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
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.
its just a minor feature on my website. if i get the code, its nice. if not, i just use german or english...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.