Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

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?

like image 851
Flash Avatar asked Sep 18 '12 11:09

Flash


People also ask

How do I return status code 204?

you may indicate that a GET endpoint that returns a collection of resources will return 204 if the collection is empty. In this case GET /complaints/year/2019/month/04 may return 204 if there are no complaints filed in April 2019. This is not an error on the client side, so we return a success status code (204).

How do I retrieve my HTTP status code?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error. Copied!

What is the meaning of the HTTP status code 204?

5 204 No Content. The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

What is the difference between 200 and 204 status code?

The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body. While 200 OK being a valid and the most common answer, returning a 204 No Content could make sense as there is absolutely nothing to return.


2 Answers

return HttpResponse(status=204) 
like image 137
Steve Mayne Avatar answered Oct 13 '22 16:10

Steve Mayne


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

like image 27
Mark Avatar answered Oct 13 '22 15:10

Mark