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
Because the pk parameter in the url is treated as str type.
Try this in urls.py:
And I recommend using get_object_or_404() (Document)
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
Let me know if this helps