Reputation: 29
I am totally new in Django and web programming and I do not even know how to ask this question precisely enough. Excuse me then if I am asking for something obvious.
I am trying to put in the same folder app two different urls in one urls.py file. I noticed that Django does not recognize them and always open the first one.
This is my app urls.py file:
from django.conf.urls import url
from second_app import views
urlpatterns = [
url(r'^$', views.help, name='help'),
url(r'^$', views.index, name='index'),
]
This is my prooject urls.py file:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', include('second_app.urls')),
url(r'^help/', include('second_app.urls'))
]
and here is my views.py that is common for both pages:
from django.shortcuts import render
from django.http import HttpResponse
def help(request):
help_dict = {'help_insert':'HELP PAGE'}
return render(request, 'second_app/help.html', context=help_dict)
def index(request):
my_dict = {'insert_me':'INDEX'}
return render(request, 'second_app/index.html', context=my_dict)
And now, when I am trying to request http://127.0.0.1:8000/help, everything works fine I can see the "HELP PAGE" but when I reqest http://127.0.0.1:8000/index nothing changes.
How can I fix it?
Thanks in advance!
Upvotes: 1
Views: 182
Reputation: 91
In your app url.py
file, both rules match the same thing. Let's analyze this. First, the project wide urls.py
:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', include('second_app.urls')),
url(r'^help/', include('second_app.urls'))
]
So, regardless of whether you are going to index/
or help/
, you end up then looking at second_app.urls
. So far, so good, that may make sense...
But then:
urlpatterns = [
url(r'^$', views.help, name='help'),
url(r'^$', views.index, name='index'),
]
Regardless of how you got here (through index/ or help/), the first rule will match if you have nothing else in the URL (after all, it has no idea how you got to this point), and you will get the help view. Given this file, there is simply no way to know you meant to go to "index". Think of this file as a single entity once you get here. It doesn't know what precedes it. It just tries to match what it is given at this point.
Upvotes: 0
Reputation: 909
You have a bad configuration in the urls, normally there are configured like that.
In your app urls file:
from django.conf.urls import url
from second_app import views
urlpatterns = [
url(r'^help/$', views.help, name='help'),
url(r'^index/$', views.index, name='index'),
]
In your project urls file:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('second_app.urls')),
]
Upvotes: 4