0

please explain me why following code works with http://127.0.0.1:8000/index/1/ and doesn't for http://127.0.0.1:8000/1/:

mysite\urls.py

urlpatterns = [
  path('index/', include('polls.urls')),
  path('1/', include ('polls.urls')),
]

polls\urls.py

urlpatterns = [
  path('1/', views.polls, name='z'),
  path('', views.index, name='index'),
]

Does Django not accept absent of some indexlike path, is everything built on it?

4
  • What do you mean by "code doesn't work for ..."? Are you getting any errors? Commented Nov 16, 2018 at 17:14
  • it shows view for '1/' only if it goes after 'index/', in the address, like 127.0.0.1:8000/index/1, and it doesn't recognize just 127.0.0.1:8000/1/, I get 404 Commented Nov 16, 2018 at 17:20
  • 1
    The full error message of the yellow debug page will tell you which paths Django tried, which will help explain what is going on. Make sure you have saved all your files and restarted the server so that you are running the code you think you are. Commented Nov 16, 2018 at 18:25
  • I've checked again, so: for 127.0.0.1:8000/index brings index view(correct), for 127.0.0.1:8000/1 also index view(not correct), and for 127.0.0.1:8000/index/1 it renders view for /1(correct). Why it recognize(shows right view) /1 only in case of /index/1? The path for '/1' pattern goes before ' ' pattern(for index), so it should be caught first. Commented Nov 16, 2018 at 19:07

2 Answers 2

2

try to use your urlpatterns in mysite to use only one path, and then map the paths inside your polls/url.py like this

mysite/urls.py

urlpatterns = [
    path('polls/', include('polls.urls')),
]

and polls/urls.py

urlpatterns = [
    path('1/', views.polls, name='z'),
    path('', views.index, name='index'),
]

if you are using class based views (CBV's) make sure to use .as_view() in your urlpatterns :) hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

it should be polls/1 and poll/ will give you the index
1

As per your code all your paths will be, http://127.0.0.1:8000/index/1/ http://127.0.0.1:8000/index/ http://127.0.0.1:8000/1/1/ http://127.0.0.1:8000/1/

From these the two urls associated with polls in your views.py are http://127.0.0.1:8000/index/1/ and http://127.0.0.1:8000/1/1/

As you have mentioned in your title http://127.0.0.1:8000/index/1/ works and http://127.0.0.1:8000/1/ does not is because you are requesting wrong url. The url you are requesting is not for views.polls change it to http://127.0.0.1:8000/1/1/. You will get your desired result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.