python / beginner
Snippet
Safe Object Retrieval
get_object_or_404 is a helper function that attempts to get an object by its primary key (pk) and handles the 'Not Found' case automatically.
snippet.py
python
1
2
3
4
5
6
7
from django.shortcuts import render, get_object_or_404from .models import Postdef post_detail(request, post_id):# Fetches the post or returns a 404 error if not foundpost = get_object_or_404(Post, pk=post_id)return render(request, 'blog/post.html', {'post': post})
django
Breakdown
1
get_object_or_404(Post, pk=post_id)
Tries to find a Post where the primary key matches the provided ID.
2
{'post': post}
Passes the found object to the template context dictionary.