首页 > 解决方案 > 如何在 Django 中返回自定义响应/状态代码?

问题描述

我想返回不同于100 <= self.status_code <= 599Django 的 HttpResponseBase类中所写的状态代码。有什么简单的方法可以绕过这个限制吗?

标签: djangohttphttp-status-codesstatus

解决方案


如果你真的想要,你可以修补.status_code属性。例如:

from django.http import HttpResponse

def some_view(request):
    response = HttpResponse('some data')
    response.status_code = 754  # sample status code
    return response

但是在 100-599 范围之外指定HTTP 状态代码 [wiki]没有多大意义,因为这些被细分为指定在什么情况下返回什么状态代码的子范围。


推荐阅读