如何通过Django Rest Framework上传图像?

时间:2017-05-23 10:48:16

标签: django django-rest-framework django-rest-viewsets

这是我的模型,其中包含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)

串行:

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

查看:

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)

因此,当我尝试通过Django Rest Framework界面上传userpic时 - 它会更新图像bu的超链接,而不会在media文件夹中创建图像文件。当我通过django管理界面上传图像时一切正常。我哪里错了?

1 个答案:

答案 0 :(得分:1)

我认为您不需要覆盖Serializer update方法。您只需在View中覆盖put,如下所示:

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)

顺便问一下,你如何从前端发送图像数据?我希望你在https://stackoverflow.com/a/32426562/2578846

中使用jquery FormData