[Django]-How to return 404 page intentionally in django

51👍

When you set debug to False, you don’t have a custom handler, and the status code of the response is 404, the 404.html (if present) in your base template directory is used. To return a response with a 404 status, you can simply return an instance of django.http.HttpResponseNotFound. The reason you got a 500 is because you raised an error instead of returning a response. So, your test function can be simply modified to this

from django.http import HttpResponseNotFound
def test(request):
    return HttpResponseNotFound("hello")         

Update:

So it turned out that the reason you are getting a 500 error was not that you raised an exception, but having incorrect function signatures. When I answered this question more than half a year ago I forgot that django catches HTTP404 exception for you. However, the handler view has different signatures than the normal views. The default handler for 404 is defaults.page_not_found(request, exception, template_name='404.html'), which takes 3 arguments. So your custom handler should actually be

def customhandler404(request, exception, template_name='404.html'):
    response = render(request, template_name)
    response.status_code = 404
    return response

Although, in this case, you may as well just use the default handler.

👤Mia

Leave a comment