Ibolit
Ibolit

Reputation: 9720

Django, custom 404/500 for when i return status_code 404 or 500

I wrote the custom 404/500 pages for my Django applications, and they work ok, except when I explicitly return response with status code 500 or 404 from my views.

In the latter case I get whatever content I return in the response. I understand that I can render my 404 and 500 templates in those responses, but is there a way to automatically use those 404/500 pages?

To illustrate my question:

When a request is sent to "http://my.host/pattern_not_matching_anything", i get my 404.html page just fine.

But, when an invalid request is received at http://my.host/valid_pattern/invalid_parameter", that is, my view gets called, I look for the parameter in the DB and don't find it, and thus I return the appropriate response:

return HttpResponse("not found", status_code=404)

The HTML page returned contains only "not found", while I expected it to render the full 404 template that I customized.

Upvotes: 2

Views: 2133

Answers (1)

Alasdair
Alasdair

Reputation: 308769

Instead of returning a response with status_code=404, you should raise a Http404 exception:

from django.http import 

def my_view(request, slug):
    try:
        obj = MyModel.object.get(slug=slug)
    except MyModel.DoesNotExist:
        raise Http404

    ...

This is a common pattern in Django, so you can use the get_object_or_404 shortcut instead.

from django.shortcuts import get_object_or_404

def my_view(request, slug):
    obj = get_object_or_404(MyModel, slug=slug)
    ...

The status code 500 is when something has gone wrong with your server. You shouldn't deliberately return a response with status code 500.

Upvotes: 5

Related Questions