Django抛出{“ non_field_errors”:[[无效的数据。应该是字典,但是有元组。“]} React JS

时间:2019-04-10 14:00:16

标签: reactjs django-rest-framework jspdf fetch-api form-data

尝试通过获取帖子将文件从react发送到django rest,但得到的django响应显示:

  

{“ non_field_errors”:[“无效的数据。应该是字典,但是有元组。”]}

我正在尝试将pdf生成的文件发送到django,但无法执行,首先我创建pdf,然后通过提取帖子请求发送

ReactJS

 genPDF=(evt)=>{

    evt.preventDefault();
   html2canvas(document.getElementById("pdfid")).then(canvas=>{
       let img=canvas.toDataURL('img/png');
       let doc=new JsPDF();
       doc.addImage(img,'JPEG',30,30);
       doc.output('blob');
       //doc.save('test.pdf');
       let formdata=new FormData();
       formdata.append('file',doc);

       fetch(`http://127.0.0.1:8000/chauffeur/pdf_upload/`,
           {
               method: 'POST',
               body:formdata,
           }
       ).then(response => response.json()).catch(error => console.error('Error:', error));

       //this.postpdf(formdata)
   });

};

DJANGO

class PdfUpload(APIView):

parser_classes = (MultiPartParser, FormParser,)

def get(self, request):
    return Response([PdfSerializer(file).data for file in Pdf.objects.all()])

def post(self,request):
    payload=(request.data,request.FILES)
    serializer=PdfSerializer(data=payload)

    if serializer.is_valid():
        serializer.save()
        return Response("File Saved in Backend",status=status.HTTP_201_CREATED)
    return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

SERIALIZER.PY

class PdfSerializer(serializers.ModelSerializer):

class Meta:
    model = Pdf
    fields = ['file',]

我发送的是正确的文件,因为它生成了PDF,然后通过获取请求将其发送,或者在Django端的formdata中可能存在问题,因为它期望字典,但是formdata充当元组?

1 个答案:

答案 0 :(得分:-1)

尝试一下:

formdata.append({'file':doc}); 

代替

formdata.append('file',doc);