Jay Cee Jay Cee - 7 months ago 54
Python Question

Why does my custom 404 page return '404 ok' response in Django?

I've to render a custom 404 template with django.
I decided to start on the basic of it:

def custom_page_not_found(request):
response = render_to_response('404.html', {},
response.status_code = 404
return response

And I'm pretty curious to know why I can't have a "404 not found". If I don't use the handler404 from urls.py, I will have the blank 404 page with the current status.
But not when I want to have a custom template.

Does anyone know why? (django 1.7.11)


In Django 1.9+, changing the status_code (e.g. to 404) will change the reason_phrase if it is not set (e.g. to 'not found'). However, you are using an older version of Django, so you would have to change the reason_phrase manually otherwise it will remain as 'ok'.

It would be easier to set the status when creating the response.

def custom_page_not_found(request):
    return render_to_response('404.html', {},

Since the render_to_response shortcut is obsolete, it would be better to use render instead.

def custom_page_not_found(request):
    return render(request, '404.html', {}, status=404)