2

I am sending a blob using Ajax. I need to save it as a file in a model.

views.py

  class JobPostModelViewSet(ModelViewSet):
      serializer_class = JobPostModelSerializer
      parser_class = (FileUploadParser, )

      def create(self, request):
          data = dict() 
          data['user'] = request.user
          data.update(request.data)

          serializer = self.serializer_class(data=data)
          if serializer.is_valid():
              serializer.save()
              return Response({'success': 'Job Posted Successfully'}, status=status.HTTP_201_CREATED)
          else:
              return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py

class JobPostModelSerializer(ModelSerializer):
    class Meta:
        model = JobPost
        fields = ("job_title", "job_description", "job_video")

Ajax.js

_postJob(e){
    var blob = this.video_blob;
    var job_title = $("#job_title").val();
    var job_description = $("#job_description").val();
    var cookie = getCookie('csrftoken');
    var formdata = new FormData();

    formdata.append('job_title', String(job_title));
    formdata.append('job_description', String(job_description));
    formdata.append('job_video', blob);

    console.log(formdata.get('job_title'));
    console.log(formdata.get('job_description'));
    console.log(formdata.get('job_video'));

    $.ajax({
        url: '/api/v1/job-post/',
        type: 'post',
        enctype: 'multipart/form-data',
        headers: {'X-CSRFToken': cookie},
        data: formdata,
        contentType: false,
        processData: false,
        success: function (e){
            console.log(e);
        },  
        error: function(e){
            console.log(e);
        },  
    }); 
}   

}

The error I get is.

{"job_title":["Not a valid string."],"job_description":["Not a valid string."],"job_video":["The submitted data was not a file. Check the encoding type on the form."]}
1
  • Try sending formdata.append("file",$("#file")[0].files[0]) instead of blob. Your input should be <input id="file" name="file" class="input-file" type="file"> Commented Jan 17, 2020 at 7:38

1 Answer 1

2

The problem is where you are trying to manipulate request.data

data = dict() 
data['user'] = request.user
data.update(request.data)

Use copy function to make a copy of request data and update it with request.user instead of vice versa. Like this

data = request.data.copy()
data['user'] = request.user

And remove parser_class attribute. It is doing no help because attribute for specifying parsers is parser_classes not parser_class.

Sign up to request clarification or add additional context in comments.

2 Comments

That really worked, didn't think manipulating the request.data object would cause me hours of pain. Really appreciate your help.
Thank you. Actually request.data is an object of specially designed QueryDict class and should only be duplicated using copy method. You can read more about it here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.