ret
ret

Reputation: 239

Django | For some error, different url show same template

I have problems with urls. For example "questions/" shows "def question_list" function well, but "subjects/" url doesn´t show "def subject_list" fucntion. For some reason "subject/" url also show question_list. why?

project>urls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('questions/', include('questions.urls')),
path('subjects/', include('questions.urls')),
]

APPquestions>urls.py

urlpatterns = [
    path('',
        views.question_list,
        name='questions',
    ),
    path('subjects/',
        views.subject_list,
        name='subjects',
    ),
]

APPquestions>views.py

def question_list(request):
    preguntas = Pregunta.objects.filter().order_by('id')
    paginator = Paginator(preguntas,1)
    page = request.GET.get('page')
    preguntas = paginator.get_page(page)
    return render(request, 'questions/questions.html', {'preguntas': preguntas})

def subject_list(request):
    categorias = Categoria.objects.all()
    return render(request, 'questions/subjects.html', {'categorias': categorias})

Upvotes: 0

Views: 28

Answers (1)

Radwan Abu-Odeh
Radwan Abu-Odeh

Reputation: 2055

This is happening simply because the two paths are referring to the same view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('questions/', include('questions.urls')), # This one
    path('subjects/', include('questions.urls')),  # And this one
]

You are including the same urls.py file in the two paths and that file has the following sub-paths

  • / ---> root of the sub-path
  • subjects/ ---> which is subjects sub-path

which means you now have 4 urls

  1. /questions/ ---> this will route you to question_list view
  2. /questions/subjects/ ---> this will route you to subject_list view
  3. /subjects/ ----> this will route you to question_list view
  4. /subjects/subjects/ ---> this will route you to subject_list view

You will always fall back to the root sub-path of questions/urls.py

It is either you use /questions/subjects/ url to get to the right view

or

re-structure you app's routes urls.

Upvotes: 1

Related Questions