91

204 No ContentDjangoビューからステータスコードを返したいのですが。これは、データベースを更新する自動POSTに応答するものであり、更新が成功したことを示す必要があります(クライアントをリダイレクトせずに)。

他のほとんどのコードを処理するためのサブクラスがありHttpResponseますが、204は処理しません。

これを行う最も簡単な方法は何ですか?

4

4 に答える 4

196
return HttpResponse(status=204)
于 2012-09-18T12:20:34.357 に答える
24

renderを使用する場合、statusキーワード引数があります。

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

(ステータス 204 の場合、レスポンス本文はありませんが、このメソッドは他のステータス コードに役立ちます。)

于 2015-07-05T14:13:54.163 に答える
21

Steve Mayne が答えたものか、HttpResponse をサブクラス化して独自のものを構築します。

from django.http import HttpResponse

class HttpResponseNoContent(HttpResponse):
    status_code = 204

def my_view(request):
    return HttpResponseNoContent()
于 2012-09-18T12:43:20.793 に答える
0

他の回答はほとんど機能しますが、コンテンツ ヘッダーがまだ含まれているため、完全に準拠した HTTP 204 応答を生成しません。これにより、WSGI 警告が発生する可能性があり、Django Web Test などのテスト ツールによって検出されます。

これは、準拠している HTTP 204 応答の改善されたクラスです。(このDjango チケットに基づく):

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()
于 2020-07-10T13:56:00.063 に答える