首页 > 解决方案 > "需要一个项目列表,但输入的是 \"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 后端,而在于我如何在前端形成列表。

标签: reactjsdjangoreact-native

解决方案


我认为您的问题是由参数中的额外花括号引起的JSON.stringify,这会创建不必要的对象。你应该改变这个:

body: JSON.stringify({eventParticipantPayload})

对此:

body: JSON.stringify(eventParticipantPayload)

推荐阅读