Skip to content

fix(blog): return 404 from post_detail when pk does not match a post#911

Open
SAY-5 wants to merge 1 commit intomemeLab:developfrom
SAY-5:fix/post-detail-404
Open

fix(blog): return 404 from post_detail when pk does not match a post#911
SAY-5 wants to merge 1 commit intomemeLab:developfrom
SAY-5:fix/post-detail-404

Conversation

@SAY-5
Copy link
Copy Markdown

@SAY-5 SAY-5 commented Apr 18, 2026

What

post_detail in src/blog/views.py called:

def post_detail(request, pk):
    post = Post.objects.prefetch_related("images", "categories").get(pk=pk)
    ...

QuerySet.get(pk=pk) raises Post.DoesNotExist when the pk does not match a row. The view did not catch it, so Django's default handler turned every missing-post request into an HTTP 500 Internal Server Error.

The route blog/post/<int:pk>/ is public, so any stale permalink, crawler, or user who types a pk that has since been deleted triggers a 500. On top of being wrong from an HTTP-semantics angle (it should be 404), it also pollutes Sentry / the server's error log with noise that masks real 500s.

Fix

Swap .get(pk=pk) for django.shortcuts.get_object_or_404 against the same prefetched queryset:

from django.shortcuts import get_object_or_404, render

def post_detail(request, pk):
    post = get_object_or_404(
        Post.objects.prefetch_related("images", "categories"),
        pk=pk,
    )
    ...

get_object_or_404 delegates to the same .get() call under the hood, so behaviour for any pk that does resolve is identical (same prefetching, same queryset). The only observable change is that a missing pk now returns a clean 404 Not Found.

Fixes #856

post_detail called Post.objects.prefetch_related("images", "categories")
.get(pk=pk) with no exception handling. When the route
`blog/post/<int:pk>/` is hit with any pk that does not correspond to an
existing row, Django raises Post.DoesNotExist. Django's default handler
turns uncaught DoesNotExist into an HTTP 500 ("Internal Server Error"),
so legitimate 404s are reported as server errors to crawlers, Sentry,
and anyone who types a stale permalink. This also makes the noise-floor
in the error tracker unusable for real bugs.

Switch to get_object_or_404 against the same prefetched queryset so the
response is a clean 404 Not Found. Behaviour is identical for any pk
that does resolve.

Fixes memeLab#856

Signed-off-by: SAY-5 <SAY-5@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

post_detail view uses Post.objects.get() without exception handling, causing HTTP 500 on missing posts

1 participant