Using Django's get_object_or_404 shortcut


Django tip:

You can use get_object_or_404 to raise the Http404 exception when the object doesn't exist instead of handling DoesNotExist and raising Http404 by yourself.

👇

from django.http import Http404
from django.shortcuts import get_object_or_404


def my_view(request):
    obj = get_object_or_404(MyModel, pk=1)


# the above is equivalent to
def my_view(request):
    try:
        obj = MyModel.objects.get(pk=1)
    except MyModel.DoesNotExist:
        raise Http404("No MyModel matches the given query.")