In a view, people often retrieve the object with the
.get(…)
[Django-doc]
call, for example:
def post_details(request, pk):
mypost = Post.objects.get(pk=pk)
# …
Why is it a problem?
If no such Post
object exists, then the
call will raise a Post.DoesNotExist
exception. If this exception is not handled properly, it
means that the server will return a HTTP 500
response, which means that the error should be at the
server side, but here the problem is at the
client side, since there simply exists no
Post
for the given primary key.
What can be done to resolve the problem?
We can make use of get_object_or_404(…)
[Django-doc].
This function will raise a Http404
exception in case the model object does not exists. This
will then be handled by Django and eventually a HTTP 404
response will be returned:
from django.shortcuts import get_object_or_404
def post_details(request, pk):
mypost = get_object_or_404(Post, pk=pk)
# …