Django urlpatterns translates from ugettext lazy - if 404, how to check again if url matches another language?

Reading for a long time, the first time I need to ask here.

The application is bilingual. I defined urls in urlpatterns to translate using ugettext_lazy. The user chooses the first language and work with the URL, if he changes lang to the second, he works well too.

But if the user selects the first language and enters the url in the second lang, he gets 404 because there is no match, because urlpatterns are translated into the first lang.

How can I get Django to check urlpatterns translated into a second language again? I want to display the page if it exists, as if the URL was entered in the first language.

I am using LocaleMiddleware.

I was thinking about setting cookies and redirecting, but if not found, the user’s URL will display the url translated into the second language, and not which user is entered, which can be misleading.

Any ideas?

Regards, Mike

Edit: I do not use these i18n templates. I like it:

url (_ (r '^ contact /'), include ('contact.urls')),

and would like Django to display the appropriate view regardless of the language chosen. If the user enters in / contact / or is translated into a second language / contact / view, should be shown.

+4
source share
1 answer

I don't really like the idea of ​​translating URLs, but try something like this:

en / django.po:

msgid "^contact/" msgstr "^en/contact/" msgid "^wrong_lang/(?P<url_part>.+)" msgstr "^ru/(?P<url_part>.+)" 

urls.py:

 url(_(r'^contact/'), include('contact.urls')), # matches "en/contact/" URL url(_(r'^wrong_lang/(?P<url_part>.+)', redirect_to_current_lang), # matches "ru/..." URLs 

views.py:

 def redirect_to_current_lang(request, url_part): return HttpResponseRedirect(_('^%s' % url_part)) 
0
source

Source: https://habr.com/ru/post/1442314/


All Articles