30👍
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.)
👤Mark
- [Django]-Django: Safely Remove Old Migrations?
- [Django]-Naming convention for Django URL, templates, models and views
- [Django]-Add inline model to django admin site
23👍
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()
- [Django]-How to create a Django queryset filter comparing two date fields in the same model
- [Django]-Django migration strategy for renaming a model and relationship fields
- [Django]-Django REST framework: non-model serializer
1👍
The other answers work mostly, but they do not produce a fully compliant HTTP 204 responses, because they still contain a content 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()
- [Django]-How to duplicate virtualenv
- [Django]-How to convert JSON data into a Python object?
- [Django]-Is it bad to have my virtualenv directory inside my git repository?
Source:stackexchange.com