【发布时间】:2021-07-13 20:21:43
【问题描述】:
我有一个用户列表,我尝试使用 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\"}"]
失败了 目的 { “non_field_errors”:数组 [ "需要一个项目列表,但输入的是 "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 后端,而在于我如何在前端形成列表。
【问题讨论】:
标签: reactjs django react-native