1

I have two django apps with URLs

app_name = 'app1'
urlpatterns = [
  path('url1/', ..., name='name1')
  path('<slug:username>/', ..., name='name2')
]

and

app_name = 'app2'
urlpatterns = [
  path('url2/', ..., name='name3')
  path('<slug:username>/action2/', ..., name='name4')
]

This would not work if I include them in the master urlpatterns as

urlpatterns = [
   path('', include('app1.urls'),
   path('', include('app2.urls'),
]

because url2/ would first match <slug:username>/ and trigger an error for unknown username.

There are a few potential solutions but none works very well for me:

  1. Use non-slug url2 such as ~url2. That means all urls in app2 has to start with something like ~ or ^.

  2. Redefine some URLs in the master urlpatterns but then I will have to import views from the apps and remove urls from the app urlpattern.

  3. Use regular expression to explicitly exclude some names from the <slug:username>. This could work but then any changes in app2 urlpatterns need to be reflected in app1's <slug:username> ... exclude certain names.

It is possible to do something like

urlpatterns = [
   path('', include('app1.urls'), # non-user part
   path('', include('app2.urls'), # non-user part
   path('', include('app1.urls'), # user part
   path('', include('app2.urls'), # user part
]

so that fixed-name URLs will be matched before <slug:username>?

user2283347
  • 670
  • 8
  • 12

1 Answers1

0

From Django docs:

include((pattern_list, app_namespace), namespace=None)

Parameters:

pattern_list – Iterable of path() and/or re_path() instances.

app_namespace (str) – Application namespace for the URL entries being included

You can include specific urls with this method:

urlpatterns = [
    path('', include(([path('url1/', <YourViewName>)], 'app1'))),
    path('', include(([path('url2/', <YourViewName>)], 'app2'))),
    path('', include(([path('<slug:username>/', <YourViewName>)], 'app1'))),
    path('', include(([path('<slug:username>/action2/', < YourViewName >)], 'app2'))),
]

First element of tuple inside include is the list of path/re_path instances that you want to include, and the second one is the app name.

Rustam Garayev
  • 2,632
  • 1
  • 9
  • 13
  • This does not appear to be working.. even without splitting my views, simply inserting ` path('', include(([], 'app1')))` before my existing `app1` URLs causes urls in `app1` to stop working. It seems that the namespace needs to be unique. – user2283347 Feb 12 '21 at 23:27