skip to Main Content

I am working on a Django project where I have a view called ‘chapterPage’ that is supposed to display a specific chapter. If the chapter with the given primary key (pk) doesn’t exist, I want to return an HttpResponseNotFound response. However, I am encountering an issue where the "Chapter not found" is not being displayed when the chapter is not found.

Code snippets:

views.py:

from django.http import HttpResponseNotFound
from .models import Chapter

def chapterPage(request, pk):
    try:
        chapter = Chapter.objects.get(id=pk)
    except Chapter.DoesNotExist:
        return HttpResponseNotFound("Chapter not found")

urls.py:

urlpatterns = [
    path("chapter/<str:pk>/", views.chapterPage, name="chapter"),
]

The chapter link on the other webpage:

 <div> 
       <a href="{% url 'chapter' chapter.pk %}">{{chapter.number}}</a>

 </div>

I made sure that the chapter exists in the database with the intended pk. Also, when I’m trying to search for a chapter using the URL ‘http://127.0.0.1:8000/chapter/5933/’ the terminal returns ‘Not Found: /chapter/5933/m’ or ‘Not Found: /chapter/5933/n’, basically an intended URL with a random character afterward.

I am expecting to get HttpResponseNotFound("Chapter not found") if the chapter is not found.

P.S. I have just started learning so any help is apreciated!

2

Answers


  1. Because the pk parameter in the url is treated as str type.

    Try this in urls.py:

    urlpatterns = [
        path("chapter/<int:pk>/", views.chapterPage, name="chapter"),
    ]
    

    And I recommend using get_object_or_404() (Document)

    from django.shortcuts import get_object_or_404
    
    def chapterPage(request, pk):
        chapter = get_object_or_404(Chapter, id=pk)
    
    Login or Signup to reply.
  2. Hi yahor the code above looks fine to be able to help further we might need to debug the possible areas, I am putting down a few let me know if you can debug those or send more details about your Django project

    1. Is there any js written that is modifying the URL
    2. Is there any middleware that is modifying it
    3. Is there any other matching view in the urls file above the one mentioned by you
    4. Lastly to debug this easily you can use pdb module and check if the request is reaching our view or not.
      Let me know if this helps
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search