M
M
marselabdullin2020-07-23 16:11:55
Django
marselabdullin, 2020-07-23 16:11:55

How to convert blob file passed through rest to django imagefield?

A picture comes to my web application via api in blob format (it is cut off by the user there) and I need to accept it, convert it to an imagefield and save it to the user.

I wrote such a code in the serializer, nothing changes and I can’t see the value of the variables either (is validated_data exactly in this format, as I think).

serializers.py:

class ProfileSerializer(serializers.ModelSerializer):
    # image = serializers.ImageField(use_url=True)

    class Meta:
        model = User
        fields = ["first_name", "last_name", "email", "image"]

    def create(self, validated_data):
        user = User.objects.get(email=validated_data['email'])
        user.update(**validated_data)

        with io.BytesIO(validated_data['image']) as stream:
            django_file = File(stream)
            user.image.save('{}_profile_image'.format(user.email), django_file)
            

        return user.save()

views.py:
class UserProfile(generics.RetrieveUpdateDestroyAPIView, generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated,)

    def get_object(self):
        queryset = self.filter_queryset(self.get_queryset())
        obj = queryset.get(pk=self.request.user.id)
        # May raise a permission denied
        self.check_object_permissions(self.request, obj)
        return obj

    def create(self, request, *args, **kwargs):
        if not request.data:
            return response.Response({"result": "data can`t be a blanks"}, status.HTTP_400_BAD_REQUEST)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return response.Response(serializer.data, status=status.HTTP_201_CREATED)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Tikhonov, 2020-07-24
@tumbler

File upload documentation not helpful?

D
Dr. Bacon, 2020-07-23
@bacon

when I was poking around there for the last time, everything was bad with the file and I had to do something in the serializer, not something likevalidated_data['image']self.context.get('view').request.FILES['image']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question