I like to raise 404 with some error message at different places in the script eg: Http404("some error msg: %s" %msg)
So, in my urls.py I included:
handler404 = Custom404.as_view()
Can anyone please tell me how should I be handling the error in my views. I'm fairly new to Django, so an example would help a lot.
Many thanks in advance.
if you want to raise some sort of static messages for a particular view , you can do as follows:-
In my case, I wanted to take some action (e.g. logging) before returning a custom 404 page. Here is the 404 handler that does it.
Note that
HttpResponseNotFound
is required. Otherwise, the response's HTTP status code is 200.I figured out a solution for Django 2.2 (2019) after a lot of the middleware changed. It is very similar to Muhammed's answer from 2013. So here it is:
middleware.py
Also, add this last to your middleware in settings.py:
'app.middleware.http404.CustomHTTP404Middleware',