Benjamin Carafa
Benjamin Carafa

Reputation: 633

Django: How do I handle urls with multiple apps

I have two apps: core and dm Here's my code:

core/urls.py

urlpatterns = [
    path('', views.index, name='index')
]

dm/urls.py

urlpatterns = [
    path('', views.dm, name='dm'),
    path('prices', views.dm_prices, name='prices')
]

mysite/urls.py

from core import views
from dm import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
    path("stripe/", include("djstripe.urls", namespace="djstripe")),
    path('dm', include('dm.urls')),
    path('dm/prices', include('dm.urls')),
]

And so, looking from the 404 page, I can see that the URLs he sees are:

  1. admin/
  2. [name='index']
  3. stripe/
  4. dm [name='dm']
  5. dm prices [name='prices']
  6. dm/prices [name='dm']
  7. dm/prices prices [name='prices']

I would be really happy if someone could explain to me how django reads the different URLs and how it orders them. Thanks a lot!

Upvotes: 3

Views: 9817

Answers (2)

interlinguex
interlinguex

Reputation: 135

It's maybe a bit outside of the scope of your question, but is the 404 page the problem you would like to solve?

As Rustam Garayev said path('dm', include('dm.urls')), django includes all urls from that file (the same applies to those in the 'core' path). That's why they appear twice. You essentially created four paths:

  • <yoursite>/dm/ (namespace dm)
  • <yoursite>/dm/prices (namespace prices)
  • <yoursite>/dm/prices (namespace dm)
  • <yoursite>/dm/prices/prices (namespace prices)

The ordering is the same as in the file that imports the apps' urls, i. e. 1 and 2 are the result from your first include statement, 3 and 4 from the second.

By the way, I realized that you're importing two views functions (core.views and dm.views) and recommend to define an alias in order to avoid name clashes in case you have methods with the same name in them.

from core import views as cviews
from dm import views as dviews

Upvotes: 3

Rustam Garayev
Rustam Garayev

Reputation: 2692

First of all, you don't need to include urls of same app twice, include('<my_app>.urls') will include all the urls you mentioned in your app's urlpatterns. So 'dm/prices' is redundant in your case, and changing it to this will do the job.

from core import views
from dm import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
    path('dm/', include('dm.urls')),
    path("stripe/", include("djstripe.urls", namespace="djstripe")),
]

For more information about include() read this django docs

Upvotes: 6

Related Questions