Hey I am trying to upload an image using Rest API[via Postman] to an object which already exists, and has all its field populated except for the image. I am using PUT method, to first get the object I want to upload the image to then trying to pass it through the serializer. The images are to be uploaded to my S3 bucket.
The code for my views.py:
@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def putproof(request):
app=MasterTaskHolder.objects.filter(title=request.data['title'],user=request.user)
serializer=ImageUploadSerializer(app,data=request.data,partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response("Posted")
My serializer:
class ImageUploadSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MasterTaskHolder
fields = (
'title','image'
)
My model:
class MasterTaskHolder(models.Model):
status_code = [
('C', 'Completed'),
('P', 'Pending'),
]
title = models.CharField(max_length=50)
point = models.IntegerField()
category = models.CharField(max_length=50, null=True, blank=True)
status = models.CharField(max_length=2, choices=status_code, default='P')
user = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(null=True, blank=True, upload_to="imageproof/")
def __str__(self):
return (f'{self.user} - ' (f'{self.title}'))
I am really new to Django and DRF, any help would be appreciated.
Thank you.
CodePudding user response:
Could you try this?
class ImageUploadSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MasterTaskHolder
fields = (
'title','image'
)
def update(self, instance: MasterTaskHolder, validated_data):
instance.image = validated_data['image']
instance.save()
return instance
In views instead of using serializer.save()
use the overrided update that we just create
serializer.update(instance, serializer.validated_data)
Also you are sending a queryset to serializer you need to change that to the object itself and humble suggestion don't forget to validate if that object exist or not.