Search code examples
djangointernationalizationcookiecutter-django

How to configure i18n_patterns in Django Cookiecutter generated urls.py?


The Django Documentation gives the following example for adding language prefixes in urls:

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')),
)

But the project-level urls.py file generated by Django Cookiecutter is the following:

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'),
    url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),

    # Django Admin, use {% url 'admin:index' %}
    url(settings.ADMIN_URL, admin.site.urls),

    # User management
    url(r'^users/', include('domainname.users.urls', namespace='users')),
    url(r'^accounts/', include('allauth.urls')),

    # Your stuff: custom urls includes go here


] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Where should I add i18n_patterns in there? Thanks a lot!


Solution

  • I did the following, so far it works:

    urlpatterns = [
        # Django Admin, use {% url 'admin:index' %}
        url(settings.ADMIN_URL, admin.site.urls),
    
        #Sitemap?
    
    ]
    
    
    urlpatterns += i18n_patterns(
        #Site pages
        url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'),
        url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),
    
        # User management
        url(r'^users/', include('domainname.users.urls', namespace='users')),
        url(r'^accounts/', include('allauth.urls')),
    
        # Your stuff: custom urls includes go here
    
    
        # Set it to False to remove 'en' prefix for English
        prefix_default_language=True
    )
    
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    I will update this answer if it breaks in the future. Please also point out any mistakes in this. Thanks!