i18n_patterns(*urls, prefix_default_language=True) [source]
This function can be used in a root URLconf and Django will automatically prepend the current active language code to all URL patterns defined within i18n_patterns().
Setting prefix_default_language to False removes the prefix from the default language (LANGUAGE_CODE). This can be useful when adding translations to existing site so that the current URLs won’t change.
Example URL patterns:
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from about import views as about_views
from news import views as news_views
from sitemap.views import sitemap
urlpatterns = [
url(r'^sitemap\.xml$', sitemap, name='sitemap-xml'),
]
news_patterns = ([
url(r'^$', news_views.index, name='index'),
url(r'^category/(?P<slug>[\w-]+)/$', news_views.category, name='category'),
url(r'^(?P<slug>[\w-]+)/$', news_views.details, name='detail'),
], 'news')
urlpatterns += i18n_patterns(
url(r'^about/$', about_views.main, name='about'),
url(r'^news/', include(news_patterns, namespace='news')),
)
After defining these URL patterns, Django will automatically add the language prefix to the URL patterns that were added by the i18n_patterns function. Example:
>>> from django.urls import reverse
>>> from django.utils.translation import activate
>>> activate('en')
>>> reverse('sitemap-xml')
'/sitemap.xml'
>>> reverse('news:index')
'/en/news/'
>>> activate('nl')
>>> reverse('news:detail', kwargs={'slug': 'news-slug'})
'/nl/news/news-slug/'
With prefix_default_language=False and LANGUAGE_CODE='en', the URLs will be:
>>> activate('en')
>>> reverse('news:index')
'/news/'
>>> activate('nl')
>>> reverse('news:index')
'/nl/news/'
The prefix_default_language parameter was added.
Warning
i18n_patterns() is only allowed in a root URLconf. Using it within an included URLconf will throw an ImproperlyConfigured exception.
In older version, using i18n_patterns in a root URLconf different from ROOT_URLCONF by setting request.urlconf wasn’t supported.
Warning
Ensure that you don’t have non-prefixed URL patterns that might collide with an automatically-added language prefix.
Please login to continue.