Jay Cee Jay Cee - 1 year ago 78
Python Question

django customepage 404 why does it return '404 ok' response

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)

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download