Detecting user language with Django

2.5k Views Asked by At

I'm looking for a way to detect user language. I set my default language as 'en_US', and I translated my site for 'pt_BR'. How can I switch the language and show 'pt_BR' version for Brazilians and 'en_US' for the rest of the world?

I read these documentation links:

https://docs.djangoproject.com/en/dev/topics/http/sessions/

https://docs.djangoproject.com/en/1.7/topics/i18n/translation/

I believe that maybe I'll have to take this information from user cookies or browser preferences, but how can I do this?

Furthermore, how can I test different languages? I have to change my browser language? OS language? Use a proxy?

3

There are 3 best solutions below

2
On

Every user's HTTP request contains in header parameter Accept-Language.

Example would be:

user_langs = request.META.get('HTTP_ACCEPT_LANGUAGE', 'en-US')
0
On

Try to add navigator.language to your post data and resolve it in your view.

http://www.w3schools.com/jsref/prop_nav_language.asp

0
On

Django detects which language it should use based on the browser settings. So changing your browser language will allow you to test.

If you set 'en_US' as default language, it will work. For more information, see: https://docs.djangoproject.com/en/4.2/topics/i18n/translation/#how-django-discovers-language-preference