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

React调用Django add_participants接口时出现“Expected a list of items but got type "dict"”错误排查求助

问题分析与解决方案

你完全说对了,问题确实出在前端的数据构造上,咱们一步步拆解并修复:

核心问题点

  1. 错误地将每个对象转为字符串:你在map里用了JSON.stringify()处理每个用户的参与数据,导致最终的eventParticipantPayload是一个字符串数组,而不是后端期望的对象数组。
  2. 额外包裹了一层对象:发送请求时,你把数组包进了{eventParticipantPayload}里,这就导致后端收到的是一个包含数组的字典,而不是直接的数组——这正好对应了你收到的错误Expected a list of items but got type "dict"。

修改后的React请求代码

const CreateNewEvent = () => {
    // 直接生成对象数组,不要对单个元素做JSON.stringify
    const eventParticipantPayload = eventParticipants.map((n) => ({
        eventName: eventTitle,
        eventLocation: eventLocation,
        eventTime: date,
        eventParticipant: n,
        votingClosed: "False"
    }));
    console.log(eventParticipantPayload) // 现在输出的是对象数组,和Postman里的格式一致
    fetch(`http://127.0.0.1:8000/api/eventsCreation/add_participants/`, {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Authorization': `Token <some token>`,
            'Content-Type': 'application/json'
        },
        // 直接将对象数组转为JSON字符串,不要包在额外的对象里
        body: JSON.stringify(eventParticipantPayload)
    })
    .then(res => res.json())
    .then(jsonRes => console.log(jsonRes))
    .catch(error => console.log(error));
}

验证修改后的请求格式

修改后,你发送的请求body会和Postman里的格式完全一致:

[ {"eventName":"Hjhjhjh","eventLocation":"Gjhgjhgjhg","eventTime":"2020-08-18T11:15:00.000Z","eventParticipant":2,"votingClosed":"False"}, {"eventName":"Hjhjhjh","eventLocation":"Gjhgjhgjhg","eventTime":"2020-08-18T11:15:00.000Z","eventParticipant":1,"votingClosed":"False"}, {"eventName":"Hjhjhjh","eventLocation":"Gjhgjhgjhg","eventTime":"2020-08-18T11:15:00.000Z","eventParticipant":3,"votingClosed":"False"} ]

这样后端的序列化器就能正确识别并处理这个数组了,请求应该就能成功返回200啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 13:53:16