如何在DRF中更新配置文件pic

时间:2017-11-08 02:57:09

标签: python django django-rest-framework

我创建了一个api,其中可以上传配置文件的图片以及其他细节。我的问题是,如果想要改变图片,怎么办呢。 目前,我可以第一次保存图片。

models.py

class Profile(models.Model):
    User = get_user_model()
    branch = models.CharField(max_length=20, null=True)
    year = models.IntegerField(null=True)
    image = models.ImageField(upload_to="accounts/images/", null=True, blank=True)
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        primary_key=False,
        null=True
    )

views.py

class ProfileView(APIView):

    permission_classes = (IsAuthenticated,)
    serializer_class = ProfileSerializer
    queryset = Profile.objects.all()

    def post(self, request, format=None):
        current_user = request.user
        param = request.data
        profile = Profile.objects.filter(user=current_user.pk)
        if profile:
            serializer = ProfileSerializer(profile, many=True)
            return Response(serializer.data)
        else:
            serializer = ProfileSerializer(data=param)
            if serializer.is_valid(raise_exception=True):
                serializer.save(user=current_user)
                new_data = serializer.data
                return Response(new_data)
            return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:2)

class ProfileView(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, format=None):
        try:
            # exist then update
            profile = Profile.objects.get(user=request.user)
            serializer = ProfileSerializer(profile, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            else:
                return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
        except Profile.DoesNotExist:
            # not exist then create
            serializer = ProfileSerializer(data=param)
            if serializer.is_valid():
                serializer.save(user=request.user)
                return Response(serializer.data)
            else:
                return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

或只使用UpdateAPIView

class ProfileView(UpdateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = ProfileSerializer
    queryset = Profile.objects.all()