Skip to navigation
Internationalization: in URL patterns in Django
27.03.24
Django provides two mechanisms to internationalize URL patterns: 1. Adding the language prefix to the root of the URL patterns to make it possible for LocaleMiddleware to detect the language to activate from the requested URL. 2. Making URL patterns themselves translatable via the django.utils.translation.gettext_lazy() function. Translating URL patterns URL patterns can also be marked translatable using the gettext_lazy() function. Example: from django.conf.urls.i18n import i18n_patterns from django.urls import include, path from django.utils.translation import gettext_lazy as _ from about import views as about_views from news import views as news_views from sitemaps.views import sitemap urlpatterns = [ path('sitemap.xml', sitemap, name='sitemap-xml'), ] news_patterns = ([ path('', news_views.index, name='index'), path(_('category/
/'), news_views.category, name='category'), path('
/', news_views.details, name='detail'), ], 'news') urlpatterns += i18n_patterns( path(_('about/'), about_views.main, name='about'), path(_('news/'), include(news_patterns, namespace='news')), ) After you’ve created the translations, the reverse() function will return the URL in the active language. Example: >>> from django.urls import reverse >>> from django.utils.translation import activate >>> activate('en') >>> reverse('news:category', kwargs={'slug': 'recent'}) '/en/news/category/recent/' >>> activate('nl') >>> reverse('news:category', kwargs={'slug': 'recent'}) '/nl/nieuws/categorie/recent/'
https://moz.pub/topics/i18n/translation.html
Reply
Anonymous
Information Epoch 1732380930
Use software leverage to your advantage.
Home
Notebook
Contact us