You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置Django测试客户端的默认content-type为application/json?

Django测试客户端默认设置application/json的最优方案

为什么直接初始化Client的方式无效

你尝试的Client(content_type="application/json")无效,是因为Django的Client构造函数本身不接受content_type参数;而Client(HTTP_CONTENT_TYPE="application/json")无效,是因为当调用post等方法时,如果没有显式指定content_type,Django会默认使用multipart/form-data作为内容类型,自动覆盖你预先设置的HTTP_CONTENT_TYPE请求头。

更优方案:自定义Client子类

相比用functools.partial修改单个方法,自定义子类的方式更易维护,还能方便扩展到put、patch等其他请求方法:

from django.test import Client

class JSONClient(Client):
    def __init__(self, *args, default_content_type="application/json", **kwargs):
        super().__init__(*args, **kwargs)
        self.default_content_type = default_content_type

    def post(self, path, data=None, content_type=None, **kwargs):
        # 优先使用传入的content_type,否则用默认值
        content_type = content_type or self.default_content_type
        return super().post(path, data=data, content_type=content_type, **kwargs)

    # 如需支持put/patch等方法,同理重写
    def put(self, path, data=None, content_type=None, **kwargs):
        content_type = content_type or self.default_content_type
        return super().put(path, data=data, content_type=content_type, **kwargs)

使用时直接实例化JSONClient即可,调用post/put方法会默认使用application/json作为内容类型:

client = JSONClient()
# 自动以application/json发送请求
response = client.post("/api/endpoint/", data={"key": "value"})
# 如需临时改用其他类型,直接传参覆盖
response = client.post("/api/form/", data={"name": "test"}, content_type="application/x-www-form-urlencoded")

保留partial方案的场景

如果只需要修改post方法且不想定义子类,你的partial写法依然可行,但注意如果后续修改了client.post的引用可能会出问题:

from functools import partial
from django.test import Client

client = Client()
client.post = partial(client.post, content_type="application/json")

内容的提问来源于stack exchange,提问作者Karel Jílek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 13:27:11