Search code examples
djangodjango-rest-frameworkdjango-rest-viewsets

How do I upload an image via Django Rest Framework?


Here is my my model containing ImageField:

class Profile(models.Model):
    user = models.OneToOneField(User)

    new_article_notifications_enabled = models.BooleanField(default=False)
    new_comment_notifications_enabled = models.BooleanField(default=False)
    new_comment_answer_notifications_enabled = models.BooleanField(default=False)

    userpic = models.ImageField(upload_to='userpics/', blank=True, null=True)
    city = models.PositiveSmallIntegerField(choices=CITY_CHOICES, default=CITY_CHOICES[0][0])
    webpage = models.URLField(blank=True)
    about_me = models.TextField(blank=True)
    favorite_brands = models.TextField(blank=True)

Serializer:

class ProfileChangeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = [
            'new_article_notifications_enabled',
            'new_comment_notifications_enabled',
            'new_comment_answer_notifications_enabled',
            'userpic',
            'city',
            'webpage',
            'about_me',
            'favorite_brands',
        ]

    def update(self, instance, validated_data):
        Profile.objects.filter(id=instance.pk).update(**validated_data)
        return instance

View:

class ProfileChangeAPIView(generics.RetrieveAPIView,
                           mixins.DestroyModelMixin,
                           mixins.UpdateModelMixin):
    permission_classes = (
        permissions.IsAuthenticated,
    )
    serializer_class = ProfileChangeSerializer
    parser_classes = (MultiPartParser, FormParser,)

    def get_object(self):
        if not Profile.objects.filter(user__id=self.request.user.pk).exists():
            return Profile.objects.create(user=self.request.user)
        return self.request.user.profile

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

So, when I trying to upload userpic via Django Rest Framework interface - it updates hyperlink to image bu does not creates image file in media folder. When I uploading image via django admin interface all works fine. Where I'm wrong?


Solution

  • I don't think you need to override Serializer update method. You can simply override put at View as follows:

    def put(self, request, *args, **kwargs):
            serializer = ProfileChangeSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    

    By the way, how you are sending image data from front-end? I hope you are using jquery FormData as in https://stackoverflow.com/a/32426562/2578846