Flash
Flash

Reputation: 16753

How can I return HTTP status code 204 from a Django view?

I want to return status code 204 No Content from a Django view. It is in response to an automatic POST which updates a database and I just need to indicate the update was successful (without redirecting the client).

There are subclasses of HttpResponse to handle most other codes but not 204.

What is the simplest way to do this?

Upvotes: 106

Views: 83284

Answers (5)

Peter Chaula
Peter Chaula

Reputation: 3721

If you're using Django Rest Framework (DRF), return a None response.

from rest_framework import status

def my_view(request):
    return Response(None, status.HTTP_204_NO_CONTENT)

Upvotes: 0

Erik Kalkoken
Erik Kalkoken

Reputation: 32852

The other answers work mostly, but they do not produce a fully compliant HTTP 204 responses, because they still contain a Content-Type header. This can result in WSGI warnings and is picked up by test tools like Django Web Test.

Here is an improved class for a HTTP 204 response that is compliant. (based on this Django ticket):

from django.http import HttpResponse

class HttpResponseNoContent(HttpResponse):
    """Special HTTP response with no content, just headers.

    The content operations are ignored.
    """

    def __init__(self, content="", mimetype=None, status=None, content_type=None):
        super().__init__(status=204)

        if "content-type" in self.headers:
            del self.headers["content-type"]

    def _set_content(self, value):
        pass

    def _get_content(self, value):
        pass

def my_view(request):
    return HttpResponseNoContent()

Upvotes: 2

Mark
Mark

Reputation: 19987

When using render, there is a status keyword argument.

return render(request, 'template.html', status=204)

(Note that in the case of status 204 there shouldn't be a response body, but this method is useful for other status codes.)

Upvotes: 29

Steve Mayne
Steve Mayne

Reputation: 22858

return HttpResponse(status=204)

Upvotes: 218

rantanplan
rantanplan

Reputation: 7450

Either what Steve Mayne answered, or build your own by subclassing HttpResponse:

from django.http import HttpResponse

class HttpResponseNoContent(HttpResponse):
    status_code = 204

def my_view(request):
    return HttpResponseNoContent()

Upvotes: 23

Related Questions