Add a prefix to URL patterns Add a prefix to URL patterns python python

Add a prefix to URL patterns


Make a pattern that looks for the common URL prefix, then include a second patterns object:

urlpatterns = patterns(    '',    url(r'^myprefix/', include(patterns(        '',        # change Language       (r'^i18n/', include('django.conf.urls.i18n')),       url('^api/v1/', include(router.urls)),       url(r'^api-docs/', RedirectView.as_view(url='/api/v1/')),       url(r'^api/', RedirectView.as_view(url='/api/v1/')),       url(r'^api/v1', RedirectView.as_view(url='/api/v1/')),       # Et cetera    ))

In fact you should perhaps group all the URLs that start with api/ this way, and definitely all the ones that start with r'^(?P<username>[^/]+)/forms/(?P<id_string>[^/]+)/'.

Edit: I didn't test that, see the documentation under "Including other URLconfs".


I found out in Django docs there is a use case for URL prefix.

In Django docs: Including other URLconfs:

We can improve this by stating the common path prefix only once and grouping the suffixes that differ:

from django.conf.urls import include, urlfrom . import viewsurlpatterns = [    url(r'^(?P<page_slug>[\w-]+)-(?P<page_id>\w+)/', include([        url(r'^history/$', views.history),        url(r'^edit/$', views.edit),        url(r'^discuss/$', views.discuss),        url(r'^permissions/$', views.permissions),    ])),]


Simply create an django app and move all your current code into that app. And finally include this urls.py into your project's urls.py. like this

url(r'^myprefix/', include('app.urls')),