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:
<
You can return a plain HttpResponse object with a status code (in this case 404)
from django.shortcuts import render_to_response
def my_view(request):
template_context = {}
# ... some code that leads to a custom 404
return render_to_response("my_template.html", template_context, status=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
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
from django.http import Http404, HttpResponse
class Custom404Middleware(object):
def process_exception(self, request, exception):
if isinstance(exception, Http404):
# implement your custom logic. You can send
# http response with any template or message
# here. unicode(exception) will give the custom
# error message that was passed.
msg = unicode(exception)
return HttpResponse(msg, status=404)
Middlewares Settings
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'college.middleware.Custom404Middleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
This will do the trick. Correct me if I am doing any thing wrong. Hope this helps.