[Fixed]-Upload image file using django rest framework in a single page application

8👍

Assuming your JS posts the request using ‘multipart/form-data‘ (check this), you should be able to upload the image file when creating or updating the user. Also, make sure you send CSRF Token.

To be able to set the logo on its own, a detailed_route is a good way using a serializer limited to the logo.
In the detailed route, if you want to upload log for logged in user (I saw you put none as an id), you can check that in the detail route before calling get_object which will get the userdetail instance.

class UserLogoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserDetail
        fields = ['profile_picture']


class UserDetailViewSet(viewsets.ModelViewSet):
    queryset = UserDetail.objects.all()
    serializer_class = UserDetailSerializer
    permission_classes = [AllowAny]

    @detail_route(methods=['post'])
    def set_profile_picture(self, request, pk=None, format=None):
        if pk in ['none', 'self']: # shortcut to update logged in user without looking for the id
            try:
                userdetail = self.get_queryset().get(user=request.user)
            except UserDetail.DoesNotExist:
                userdetail = None
        else:
            userdetail = self.get_object()

        serializer = serializers.UserLogoSerializer(userdetail, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)            

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

If I recall correctly, permission_classes are the one set on the Viewset by default, and the default parsers should do the job.

4👍

Leave a comment