使用Django Rest Framework将输入文件从Vue.js发送到Django时出现问题

时间:2019-03-11 10:05:44

标签: django vue.js django-rest-framework axios

我正在尝试使用DRF从Vue.js向Django发送表单。但是响应是400 Patch错误:

{"file":["The submitted data was not a file. Check the encoding type on the form."]}

这是我在Vue.js中的模板: 模板:

  <input type="file" id="file" ref="file" class="input is-rounded" v-on:change="handleFileUpload()"/>

这是Vue方法。我发送enctype:“ multipart / form-data”,我认为我使用的是发送文件的正确方法。无论如何,我认为这是问题所在,也许this.file没有正确发送文件。

HTTP是Axios的常量:“ const HTTP = axios.create({})”

 methods: {
 handleFileUpload(){
    this.file = this.$refs.file.files[0];
  },
 create: function () {
  this.token = this.$store.state.access_token;

    HTTP({
      method: 'PATCH',
      url: 'tickets/create/',
      enctype: 'multipart/form-data',
      headers: {
        'Authorization': `Bearer ${this.token}`,
      },
      data: {
        file:this.file,
      }
    })
    .then(response => { ...

这是我的view.py方法:

  @csrf_exempt
  @api_view(['GET', 'POST','PATCH'])
  def Create(request):
     parser_classes = (FileUploadParser,)

  if request.method == 'PATCH' or request.method == 'POST':


    serializer = CreateTicketSerializer(
        Tickets,
        data=request.data
    )
    serializer.is_valid(raise_exception=True)

    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#Return this if request method is not POST
return Response({'ok': 'false'}, status=status.HTTP_200_OK)

还有我的序列化器:

 class CreateTicketSerializer(serializers.ModelSerializer):
    """Ticket serializer."""


   file = serializers.ImageField(required=False,max_length=None, use_url=True)

class Meta:
    model = Tickets
    fields = (
        'file',
    )

0 个答案:

没有答案