Jay Cee Jay Cee - 24 days ago 12
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', {},
context_instance=RequestContext(request))
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

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', {},
                              context_instance=RequestContext(request),
                              status=404)

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)
Comments