[Fixed]-Add a prefix to URL patterns

18👍

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”.

12👍

For django 2+ it is now

from django.conf.urls import include
.
.
.
urlpatterns = [
... # Your URL patterns
]
# Add 'prefix' to all urlpatterns
urlpatterns = [path(r'^prefix/', include(urlpatterns))]

I am using this with a setting so that I can deploy to different environments easily this is how I am doing that.

from django.conf.urls import include
from django.conf import settings
.
.
urlpatterns = [
... # Your URL patterns
]
# Add 'prefix' to all urlpatterns
if settings.URL_PREFIX:
    urlpatterns = [path(f'{settings.URL_PREFIX}/', include(urlpatterns))]

URL_PREFIX has to be designated in the settings as well.

10👍

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

10👍

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, url
from . import views

urlpatterns = [
    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),
    ])),
]

8👍

If you want just add a prefix for all URLs you can use the following code in urls.py file:

from django.conf.urls import include
.
.
.
urlpatterns = [
... # Your URL patterns
]
# Add 'prefix' to all urlpatterns
urlpatterns = [url(r'^prefix/', include(urlpatterns))]

It’ll add prefix for all urlpatterns.

Leave a comment