Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change language from Django URL?

I want to change the language when the user introduce in the url the locale, something like this http://example.com/es/, http://example.com/es/article-name, http://example.com/en/.

how can I do that?

like image 256
eos87 Avatar asked Jun 10 '10 00:06

eos87


People also ask

What is Django URL reverse?

the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. Syntax: Web development, programming languages, Software testing & others. from django.urls import reverse.

What is URL config in Django?

In Django, we use something called URLconf (URL configuration). URLconf is a set of patterns that Django will try to match the requested URL to find the correct view.

Is URL and path same in Django?

The path function is contained with the django. urls module within the Django project code base. path is used for routing URLs to the appropriate view functions within a Django application using the URL dispatcher.


3 Answers

Checkout django-locale-url.

It provides a middleware that does exactly what you are asking for, so you don't need to check for the language in urls.py

like image 181
DanJ Avatar answered Oct 21 '22 08:10

DanJ


A number of ways to do this that come to mind. Arguably the most "standards compliant" way would be to use the HTTP Accept-Language header, which is available to views as request.META['HTTP_ACCEPT_LANGUAGE'] to determine the language in which the user prefers to receive resources and simply return a translated HttpResponse in the appropriate language.

Another common way, more along the lines of what you are describing, is to ask the user to select a language on their first arrival and store the selection in the session. Once the user makes a choice, redirect the browser to the appropriate language subdirectory and use relative links in your views so as not to have to worry about crossing languages. You can adjust your URLconf to pass a language keyword to your view like so:

urlpatterns = patterns('',
    (r'^(?P<lang>[a-zA-Z]{2})/ ...

There is an Internationalization/Localization page on the Django documentation site about i18n that might help you get started.

like image 3
AdmiralNemo Avatar answered Oct 21 '22 08:10

AdmiralNemo


Nowadays the best way is using the built-in language prefix in url patterns: https://docs.djangoproject.com/en/1.8/topics/i18n/translation/#language-prefix-in-url-patterns

like image 3
chaim Avatar answered Oct 21 '22 09:10

chaim