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.
Yes we can show specific exception message when raise Http404.
Pass some exception message like this
Add 404.html page into templates directory.
templates/404.html
You can return a plain HttpResponse object with a status code (in this case 404)
The default 404 handler calls 404.html . You could edit that if you don't need anything fancy or can override the 404 handler by setting the handler404 view -- see more here
In general, 404 error is "page not found" error - it should not have customizable messages, simply because it should be raised only when a page is not found.
You can return a
TemplateResponse
with status parameter set to404
Raise an
Http404
exception inside a view. It's usually done when you catch aDoesNotExist
exception. For example:Even better, use
get_object_or_404
shortcut:If you'd like to customize the default
404 Page not found
response, put your own template called404.html
to thetemplates
folder.Generally there should not be any custom messages in 404 errors bu if you want to implement it you can do this using django middlewares.
Middleware
Middlewares Settings
This will do the trick. Correct me if I am doing any thing wrong. Hope this helps.