Jeffrey Swan
Jeffrey Swan

Reputation: 537

Django urlpatterns/include() loading wrong view

Website has a homepage in addition to several data-driven apps. No problem. But as I'm trying to add in other non-data-driven pages (about, mission statement, etc) I'm having trouble with by url directs.

settings.py url patterns includes:

url(r'^$', include('home.urls')),
url(r'^mission/$', include('home.urls')),

home/urls.py includes:

url(r'^$', views.index, name='index'),
url(r'^mission/$', views.mission, name='mission'),

Directing the browser to the homepage loads the index view as it should, but directing the browser to /mission/ also loads the index view.

I realize I'm probably missing something small (and fundamental) here, but I've read over the docs for the hundredth time and read about a lot of other people's questions about urlpatterns, but I just can't figure out what's going on. The include() statement in settings.py doesn't seem to be the problem. Since the home index view loads it's obviously being directed to home/urls.py, and that file is so simple that I just can't see what the problem would be.

Could someone please educate me so I can move on to my next Django brick to the face? I appreciate it.


SOLVED - Thank you Sohan Jain

Actual issue was use of r'^$' in settings URLPATTERNS rather than r''. Use of the second include() statement was attempt to work around actual issue.

Upvotes: 0

Views: 858

Answers (1)

Sohan Jain
Sohan Jain

Reputation: 2377

When you include urls from another directory, their path must start with the first parameter.

So when you say url(r'^$', include('home.urls')), that means: for each url in home.urls, make its path start with ^$, i.e nothing.

And when you say url(r'^mission/$', include('home.urls')), that means: for each url in home.urls, make its path start with 'mission'.

And urls are matched in order. So navigating to /mission/ matches url(r'^mission/$', include('home.urls')) and then url(r'^$', views.index, name='index'), which yields the index page.

Here's what you want:

settings.py 
url(r'', include('home.urls'))

home/urls.py
url(r'^$', views.index, name='index'),
url(r'^mission/$', views.mission, name='mission'),

Upvotes: 2

Related Questions