I have a DJango application that have several entries in URL patterns (urls.py):
urlpatterns = patterns(
\'\',
# change Language
(r\'^i18n/\', in
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.
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.
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')),
I found out in django docs there is a use case for url prefix.
In django docs (https://docs.djangoproject.com/en/1.11/topics/http/urls/#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),
])),
]
Hope this can be helpful for you.
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".