0

I am trying to upload an image using a vue component and django rest framework. Here is a snippet of the html

<div class="mb-3 mx-5">
            <label for="image" class="form-label">Upload an image that best describes the survey</label>
            <input class="form-control" type="file" ref="file" name="image" id="image" @change="onFileSelected()">
        </div>

And here are my vue methods that am using to send data to the backend

 methods: {
        onFileSelected() {
            this.image = this.$refs.file.files.item(0)
        },
        sendData (file) {
            const formData = new FormData()
            formData.append('image', file)
            axios.post('/api/v1/surveys/', this.SurveyList, formData, {
                headers: {
                    "Content-Type": "multipart/form-data",
                    "X-CSRFToken": "{{ csrf_token }}"
                }
            })
            
            .then(response => {
                this.SurveyList = response.data
            })
            .catch(error => {
                console.log(error)
            })
        }
    }

I was getting the following error The submitted data was not a file and then tried implementing the changes discussed here Django REST Framework upload image: "The submitted data was not a file" But now I get this error This field may not be null. Here is my serializer.py

class SurveySerializer(serializers.ModelSerializer):
    image = Base64ImageField(
        max_length=None, use_url=True,
    )
    class Meta:
        model = Survey
        fields = (
            "id",
            "category",
            "description", 
            "location", 
            "image", 
            "question1",
            "questiontype1",
            "choice1a",
            "choice2a",
            "choice3a",
            "choice4a",
        )

And here is my views.py

  def post(self, request, format=None):
        serializer = SurveySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return  Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

What could be the issue?

Felicity
  • 151
  • 10
  • You should not explicitly set the `Content-Type` header in Axios - it will be set automatically. – IVO GELOV Sep 17 '22 at 16:55
  • still raises the same erros, with or without – Felicity Sep 17 '22 at 17:47
  • Inspect the HTTP traffic - either from DevTools or with Fiddler. Then post the result here. Try with a small file, e.g. 100-200 bytes. – IVO GELOV Sep 20 '22 at 15:44
  • I had already added what I am getting from the network requests `{image: ["This field may not be null."]} image : ["This field may not be null."]` – Felicity Sep 22 '22 at 21:35
  • Oh, then I have been misled by the `vue` tag on the question. It looks like this has nothing to do with Vue. – IVO GELOV Sep 23 '22 at 09:55

0 Answers0