Home > Back-end >  How to upload an image using a post api in django
How to upload an image using a post api in django

Time:01-16

I am working on a project using django 3.1 for backend and vue 3 for frontend. I am pretty new to Django so I am still learning the ropes and I do not know if what I am trying is totally wrong.

I created a model that holds a user email and and an image field as follows:

class UsedBike(models.Model):
    sellerEmail = models.CharField(max_length=255)
    image = models.ImageField(upload_to='uploads/', blank=True, null=True)

    class Meta:
        ordering = ('sellerEmail', )

    def __str__(self):
        return self.sellerEmail

    def get_image(self):
        if self.image:
            return 'http://127.0.0.1:8000'   self.image.url
        return ''

I created a serializer for my model as follows:

class UsedBikeSerializer(serializers.ModelSerializer):
    class Meta:
        model = UsedBike
        fields = (
            "id",
            "sellerEmail",
            "get_image",
        )

and in the views file, I created a function for saving the data in the database:

@api_view(['POST'])
def sellBike(request):
    serializer = UsedBikeSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)

I also registered the url in the urls file.

As for vue part, I used axios to send my post request as follows:

submitData() {
            const formData = {
                sellerEmail: this.sellerEmail,
                image: this.productImage
            }
            axios
                .post("/api/v1/sell-bike/", formData)
                .then(response => {
                    console.log(response)
                }).catch(error => {
                    console.log(error)

                })
        },

where in the template I am getting the inputs like this:

<input type="text" v-model="sellerEmail">
<input type="file" accept="image/png, image/jpeg" id="imageInput" v-on:change="onFileChange()">
<button @click="submitData">Upload</button>

and the method onFileChange is:

onFileChange(e) {
            let imageInput = document.getElementById("imageInput")
            this.productImage = imageInput.files[0]
        },

When I send the request, I get "POST /api/v1/sell-bike/ HTTP/1.1" 200 55 in the django terminal. However, If I print request.data I get the following:

{'sellerEmail': '[email protected]', 'image': {}}

As you can see, image is empty and when I checked the database, the email part is filled correctly but image is empty.

How can I solve this problem? Any help is appreciated.

CodePudding user response:

IN your axios call, you need to include the below header as well:

submitData() {
            const formData = new FormData();
            formData.append('sellerEmail', this.sellerEmail);
            formData.append('image', this.productImage);
            const headers = {headers: { 'Content-Type': 'multipart/form-data' }}
            axios
                .post("/api/v1/sell-bike/", formData, headers)
                .then(response => {
                    console.log(response)
                }).catch(error => {
                    console.log(error)

                })
        }

Also, to save image to database, you also need to include the "image" in fields inside UsedBikeSerializer

  • Related