2

I am trying to send a form from Vue.js to Django with DRF. But the response is 400 Patch error:

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

It is my template in Vue.js: Template:

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

And here is Vue methods. I send enctype: 'multipart/form-data' and I think that I am using the correct way to send the file. Anyway, I think that here is the problem, maybe this.file is not sending the file correctly.

HTTP is a constant to 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 => { ...

And here my view.py method:

  @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)

And my Serializer:

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


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

class Meta:
    model = Tickets
    fields = (
        'file',
    )
Miguel Herreros Cejas
  • 664
  • 1
  • 12
  • 28
  • Possible duplicate of [Ajax post a file from a form with Axios](https://stackoverflow.com/questions/43013858/ajax-post-a-file-from-a-form-with-axios) – Flame Mar 11 '19 at 11:43
  • Flame, thanks for your answer. The solution maybe is the same but I did not know if the problem was in Javascript or in Django. – Miguel Herreros Cejas Mar 11 '19 at 15:02

1 Answers1

1

You need to use FormData API to construct a set of key/value pairs representing form fields and their values:

create: function () {
    this.token = this.$store.state.access_token;

    let data = new FormData(); // creates a new FormData object
    data.append('file', this.file); // add your file to form data

    HTTP({
      method: 'PATCH',
      url: 'tickets/create/',
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'content-type': 'multipart/form-data'
      },
      data
    })
    .then(response => { ...
mehamasum
  • 5,554
  • 2
  • 21
  • 30