Django cannot find page with multiple similar URL paths

I am trying to create a Django site with different views/models spanning from the same level of the URL structure.

Here is the URL structure I am trying to create:

  • HOME PAGE -- Country --- State ---- City --- Topic ---- Article

I am using the following code in urls.py:

urlpatterns = [
    path(
        "<slug:country_slug>/<slug:state_slug>/<slug:city_slug>/",
        CityIndex.as_view(),
        name="city_index",
    ),
    path(
        "<slug:country_slug>/<slug:topic_slug>/<slug:article_slug>/",
        ArticleDetail.as_view(),
        name="article_detail",
    ),
    path(
        "",
        HomeIndex.as_view(),
        name="home",
    ),

The City Index path works fine. The issue I have is trying to access an article. Django only seems to attempt to match the first URL path. I enter a URL: "example-country/example-topic/example-article"

Django returns the following error message:

Page not found (404)

No Destination matches the given query.

Request Method:     GET
Request URL:    http://127.0.0.1:8000/example-country/example-topic/example-article/
Raised by:  content.views.destinations.CityIndex

It seems that, because the pattern is similar to the URL pattern for "city_index", it attempts to match this, then return a 404 error. It doesn't move on to check the next URL pattern for "article_detail", which would then match an article and return a template.

I tried switching the "article_detail" URL path to come first, above "city_index".
This causes "article_detail" to return a template correctly, but now "city_index" does not.

Effectively, Django will match a URL for whichever comes first, but then the second URL pattern returns a 404.

Thanks for your help with this!

Back to Top