Search code examples
djangodjango-viewsdjango-urls

URL not matching url pattern in Django


I'm trying to learn Django, went through the official tutorial and giving it a try on my own. I've created a new app and can access the index page but I can't use pattern matching to go to any other page. Here is my monthlyreport/url.py

from django.urls import path

from . import views

#app_name = 'monthlyreport'

urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
] 

and my monthlyreport/views

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic

from .models import Report

def index(request):
    report_list = Report.objects.all()[:5]
    template = loader.get_template('monthlyreport/index.html')
    context = {
        'report_list': report_list,
    } 
    return HttpResponse(template.render(context, request))
    
def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

The debug for http://127.0.0.1:8000/monthlyreport/0 is showing

 Using the URLconf defined in maxhelp.urls, Django tried these URL patterns, in this order:
 
 monthlyreport [name='index']
 monthlyreport <int:question_id>/ [name='detail']
 polls/
 admin/
 accounts/

 The current path, monthlyreport/0, didn’t match any of these.

Again, using http://127.0.0.1:8000/monthlyreport/ to go to index works fine, but I cant match the integer. I would really appreciate any suggestions, I am very, very confused at this point.


Solution

  • Problem with your code is of one slash(/). In your root urls.py file, from where you must have used something like:

    path('monthlyreport', include('monthlyreport.url'))
    

    So, the problem here is that you should have ending / in your path if you are setting your urls in monthlyreport.url like:

    urlpatterns = [
        path('', views.index, name='index'),
        path('<int:question_id>/', views.detail, name='detail'),
    ] 
    

    Or else, you have to put slash(/) infront of every new path like:

    urlpatterns = [
        path('', views.index, name='index'),
        path('/<int:question_id>/', views.detail, name='detail'),
              |
              |
              V
            Here
    ]
    

    Solution

    In summary, convinient solution is adding slash(/) after path in urls.py file. Like:

    path('monthlyreport/', include('monthlyreport.url'))
                       |
                       |
                       |
                       V
                 Add slash here