Almost every detail view in Django starts with the same job: fetch a record by id or slug, and return a 404 when it does not exist. Instead of writing try/except DoesNotExist and raising Http404 by hand, you only need one line — get_object_or_404(Model, **lookup). It returns the record when it exists and raises Http404 when it does not. The result is shorter, harder to get wrong, and works for every model from the earliest Django versions up to the current 6.x releases.

The Problem

Suppose you have a post detail page addressed by slug. The familiar hand-written approach is to call get() inside a try/except block:

from django.http import Http404
from django.shortcuts import render
from .models import Post
def post_detail(request, slug):
try:
post = Post.objects.get(slug=slug)
except Post.DoesNotExist:
raise Http404("Bài viết không tồn tại")
return render(request, "blog/post_detail.html", {"post": post})

The problem is not that this code is wrong — it works. The problem is that it is long, repeated in every view, and a single forgotten raise Http404 turns a friendly 404 page into a 500 error for the user. Once a project has dozens of detail views, this try/except pattern is duplicated everywhere and the code gets harder to read and harder to review.

The Solution

Django already ships this pattern in django.shortcuts:

from django.shortcuts import get_object_or_404, render
from .models import Post
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
return render(request, "blog/post_detail.html", {"post": post})

Under the hood, the function calls queryset.get(), catches DoesNotExist and raises Http404 — exactly the manual pattern, but you never have to write it again. It accepts every lookup argument filter() does: slug, pk, author__username, and more. It also has a sibling, get_list_or_404(), for filtered list pages: if the queryset is empty, it returns a 404 instead of a blank page.

One small warning: do not use get_object_or_404() to check permissions. It only checks existence, not whether the user is allowed to see the record. To stop strangers from editing someone else’s post, filter by the user right inside the lookup:

# Chỉ lấy bài đã xuất bản
post = get_object_or_404(
Post.objects.filter(status="published"),
slug=slug,
)
# View sửa/xóa: chỉ chủ bài mới được xem
post = get_object_or_404(Post, slug=slug, author=request.user)
# Trang danh sách: không có bài nào thì 404
from django.shortcuts import get_list_or_404
posts = get_list_or_404(Post, category__slug=category_slug)

Apply It to Your Project

Apply this to your own project right away: review your detail views (view, edit, delete) and replace every try/except DoesNotExist block with get_object_or_404(). Pair it with a custom 404.html template in your templates directory so the error page carries your own branding instead of Django’s default. For edit or delete views, pass the ownership condition into the lookup as well, so one query checks both existence and permission — no extra if statement needed.

Related Posts

FAQ

How is get_object_or_404() different from plain get()?

get() raises DoesNotExist when no record matches — if you do not catch it, Django returns a 500 error. get_object_or_404() catches that exception for you and raises Http404 instead, so the user sees a proper 404 page.

Can I use it with a queryset that is already filtered?

Yes. Instead of passing a model, pass a queryset: get_object_or_404(Post.objects.filter(status=”published”), slug=slug). This is useful when you only want records that satisfy an extra condition, for example only published posts.

When should I use get_list_or_404()?

When a list page is filtered by a condition and an empty result means that condition does not exist — for example a category page with no posts. A 404 is more honest there than an empty page that makes users think the page is broken.

Do I still need try/except?

No, unless you want special handling — for example logging the miss or redirecting somewhere else instead of returning a 404. If all you need is a standard 404 page, get_object_or_404() already handles it.

💬 Have you tried this approach in your own project? If you ran into an error or know a more concise way to do it, leave a comment below — I read every one and will add the best ideas to the post.

References