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

如何在Django测试中发送带查询参数的图片字段POST请求

Django REST Framework测试POST请求的查询参数与图片上传问题解决方案

原始测试代码

from rest_framework.test import APITestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse

class PostImageTest(APITestCase):
    def setUp() -> None:
        self.product = Product.objects.create(...)
        self.sampleImage = SimpleUploadedFile("test_image.jpg", b"binary data", content_type="image/jpeg")

    def test_with_valid_data() -> None:
        data = { "image":self.sampleImage, "is_featured":True }
        response = client.post(reverse('images'), data, format='multipart')

问题描述

需要给POST请求传递类似images?product=id的查询参数,同时正确发送图片数据,但尝试以下写法时触发错误:

response = client.post(reverse('images'), {'product' : self.product.id}, data=data, format='multipart')

错误信息:TypeError: Client.post() got multiple values for argument 'data'

解决方案

核心原因

DRF测试客户端的post方法中,第二个位置参数默认对应data参数,你同时传递了位置参数形式的data和关键字参数形式的data,导致参数冲突。查询参数需要通过专门的参数传递,或者直接拼接到URL中。

正确写法

1. 使用params参数(DRF 3.10+ 推荐)

def test_with_valid_data(self) -> None:
    data = { "image": self.sampleImage, "is_featured": True }
    response = self.client.post(
        reverse('images'),
        data=data,
        params={'product': self.product.id},
        format='multipart'
    )

2. 使用QUERY_PARAMS参数(旧版本DRF)

def test_with_valid_data(self) -> None:
    data = { "image": self.sampleImage, "is_featured": True }
    response = self.client.post(
        reverse('images'),
        data=data,
        QUERY_PARAMS={'product': self.product.id},
        format='multipart'
    )

3. 直接拼接查询参数到URL

def test_with_valid_data(self) -> None:
    data = { "image": self.sampleImage, "is_featured": True }
    url = f"{reverse('images')}?product={self.product.id}"
    response = self.client.post(url, data=data, format='multipart')

额外注意点

  • 代码中client需改为self.client(因为是APITestCase的实例方法);
  • Python布尔值需用True而非JavaScript风格的true。

内容的提问来源于stack exchange,提问作者Srivatsa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:42:22