reactjs - "需要一个项目列表,但输入的是 \"dict\"。",
问题描述
我有一个用户列表,我尝试使用 add_participants 端点为其添加到事件中。
我的 Django 视图集:
class EventsCreationViewSet(viewsets.ModelViewSet):
queryset = Event.objects.all()
authentication_classes = (TokenAuthentication, )
@action(detail=False, methods=['POST']) #detail means we want to accept details (a specific Movie), not just "/"
def add_participants(self, request, pk=None):
serialized = EventCreationSerializer(data=request.data, many=True)
if serialized.is_valid():
serialized.save()
return Response(serialized.data)
else:
return Response(serialized._errors)
我的反应方法:
const CreateNewEvent = () => {
#Create an entry for each user in list
const eventParticipantPayload = eventParticipants.map((n) => JSON.stringify({ eventName: eventTitle, eventLocation: eventLocation, eventTime: date, eventParticipant: n, votingClosed: "False" }));
console.log(JSON.stringify(eventParticipantPayload))
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'
},
body: JSON.stringify({eventParticipantPayload})
})
.then(res => res.json())
.then(jsonRes => console.log(jsonRes))
.catch(error => console.log(error));
我来自 console.log 的请求数据
["{\"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\"}"]
Object { "non_field_errors": Array [ "Expected a list of items but got type "dict".", ], }
但是..从 POSTMAN 发布以下内容时,我得到 200 并且我的条目被添加
[
{"eventName":"swimming","eventLocation":"Xsport","eventTime":"2020-08-20T11:15:00.000Z","eventParticipant":2,"votingClosed":"False"},
{"eventName":"swimming","eventLocation":"Xsport","eventTime":"2020-08-20T11:15:00.000Z","eventParticipant":3,"votingClosed":"False"}
]
所以我认为问题不在于我的 Django 后端,而在于我如何在前端形成列表。
解决方案
我认为您的问题是由参数中的额外花括号引起的JSON.stringify
,这会创建不必要的对象。你应该改变这个:
body: JSON.stringify({eventParticipantPayload})
对此:
body: JSON.stringify(eventParticipantPayload)
推荐阅读
- intellij-idea - 如何增加 IntelliJ 中悬停文档的超时时间?
- python - ValueError:“conv3d_3/convolution”(操作:“Conv3D”)从 1 中减去 22 导致的负尺寸大小
- jquery - 动态下拉菜单不做条件语句
- acumatica - Acumatica - 如何返回 SalesInvoice 的最后修改日期?
- pywinauto - 如何在 Windows 开始菜单中获取元素的 top_level_parent()?
- reactjs - react-bootstrap-table2的边框上怎么可以设置一个图标
- python - 如何检查函数是在 IDLE 中运行还是从另一个函数/模块运行
- android - Kotlin 扩展属性在某些应用程序模块中被识别,而在其他模块中不被识别
- javascript - js.erb 文件在尝试渲染部分时抛出“错误:rails-erb-loader failed with code: 1”错误
- css - 在 WordPress 中使用 css 在文本旁边对齐字体真棒图标