Django: URL pattern conversion with gettext

In some Django applications, I found URL patterns with gettext, for example:

from django.utils.translation import ugettext as _ urlpatterns = patterns('', ... url(r'^%s$' % _('about/'), about, name='about'), ... ) 

Firstly, it would be nice to have universal URLs in the same way with the rest of the project, but I have doubts.

AFAIK, URL patterns are loaded when the application starts. Therefore, I suspect that they will be created in accordance with the language preferences of the user who makes the first request to the application. This can become even more unpredictable when threads are also in the game.

This approach may be reasonable in cases where the installation will be in one language, but there may be other installations in other languages, for example, in forums.

Do you think this is a problem or just my imagination? Can this approach be used for multilingual sites? Can ugettext_lazy avoid this problem?

+4
source share
4 answers

This approach will not work. Your translation is executed when the application loads. This means that your URL patterns will have one language, the default language of your application.

Translations work only when the context from which they are called has access to user language preferences.

In order for your URLs to be multilingual, you need to use some URL definitions at runtime. They will be downloaded based on the user's current language.

+1
source

Read the django docs: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#url-internationalization

Basically, you can use ugettext_lazy to translate your templates, and it will work if a language is set for each request. To ensure this, you must use LocaleMiddleware. https://docs.djangoproject.com/en/dev/ref/middleware/#django.middleware.locale.LocaleMiddleware

+3
source

You are right when ugettext_lazy is evaluated immediately upon string concatenation.

Sth how it works: url (_ (r '^ contact /'), include ('contact.urls')),

But you need to translate patterns that may be erroneous.

0
source

You can do it as follows:

 import six from django.utils.functional import lazy def lazy_url_pattern(pattern): return lazy(pattern, six.text_type)() 

And then in the manager:

 urlpatterns = [ url(lazy_url_pattern(lambda: r'^{n}/$'.format(n=ugettext_lazy(u'foo'))), MyView.as_view(), name='...'), 

But it is still error prone though ....

Floor

0
source

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


All Articles