Search code examples
djangohttp-status-code-404django-messages

When to use messages or 404 in django


I have a doubt when using django.contrib.messages or showing a 404 page. In which case do I should use one or the another?

serial = get_object_or_404(SerialNumber, serial_number=sn)

or

try:
    serial = SerialNumber.objects.get(serial_number=sn)
except SerialNumber.DoesNotExist
    messages.add_message(request, messages.WARNING, 'no found!')

Thanks in advance!


Solution

  • Let's say you have some url like this:

    /article/<pk>/
    

    If a end-user calls /article/5/ and there is no article with ID 5, then you should not only return a message, that the searched term is not found, but also the proper HTTP status code, which is 404. Here you should use get_object_or_404.

    If you want to display some additional information on the page for /article/4/ and there is article with ID 4, but this particular additional information is not there, then you should display the page for article with ID 4, return HTTP status code 200, which means OK, and display the message, that the additional information is not available.

    The main difference is in my opinion the proper handling of the HTTP status codes, but I let others teach me, if I'm wrong.