Reputation: 1091
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!
Upvotes: 0
Views: 112
Reputation: 239
A 404 page page should be displayed when the user is trying to access any resource that is not available on the server. On the other hand django messaging is used when you want to let the user see your application related custom messages. for example when he deletes or updates an entry you can show him a delete/update successful message.
Upvotes: 1
Reputation: 182
In my opinion, the main difference between 404 error and Django messages framework is that the 404 is related to the server, and messages are related to your application.
In other words, if a user requires an url which does not exist (ie. /url/which/doesnt/exist/) then the server should send a 404. But if a user requires a feature of your application which can fail or which gives info or debug messages (/articles/feature_acting_on_article_db/), then you should use messages framework.
As you can see in documentation https://docs.djangoproject.com/en/1.7/ref/contrib/messages/, messages are used at application level. The definition of 404 error is given by: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5:
(...)This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.
To conclude, I would say that the proper way to handle a url like /article/5/ where there is no 5th article is to send a message, because /article/pk/ is a feature which selects and displays info of the pk'th article (and no article doesn't mean that the command failed), even if the user entered a url (but that's my point of view about this question).
Upvotes: 1
Reputation: 12012
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.
Upvotes: 2