Skip to content

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

@vjpixel

Description

@vjpixel

Description

In src/blog/views.py, the post_detail() view calls Post.objects.get(pk=pk) without any exception handling. If the provided pk does not match any post in the database, Django raises an unhandled Post.DoesNotExist exception, resulting in an HTTP 500 error instead of a proper 404 response.

Location

File: src/blog/views.py
Function: post_detail()
Branch: develop

Current Code

def post_detail(request, pk):
    post = Post.objects.prefetch_related("images", "categories").get(pk=pk)
    # No exception handling — raises DoesNotExist if pk not found
    context = {"post": post, "images": post.images.all()}
    return render(request, "blog/detail.jinja2", context)

Problem

  • If pk refers to a non-existent post, Post.DoesNotExist is raised.
  • This results in an HTTP 500 Internal Server Error instead of a clean 404 Not Found.
  • Any crawler, bot, or user who navigates to /memories/99999/ can trigger an unhandled server error.

Suggested Fix

from django.shortcuts import get_object_or_404

def post_detail(request, pk):
    post = get_object_or_404(
        Post.objects.prefetch_related("images", "categories"),
        pk=pk
    )
    context = {"post": post, "images": post.images.all()}
    return render(request, "blog/detail.jinja2", context)

Severity

Medium — Any request with a non-existent post ID causes an unhandled HTTP 500 error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    backendbugSomething isn't workingpriority: highHigh priority - should be addressed soonpriority: mediumMedium priority - standard priority

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions