[Django]-Upload multiple image and associate to property

1πŸ‘

βœ…

If you remove the line,

parser_classes = (FileUploadParser,)

the serializer fields would be shown.

Since, you have written a view updating existing objects, you may need to raise exception if an object doesn’t exist with a particular id. You could use the shortcut function get_object_or_404() for that.

from django.shortcuts import get_object_or_404

def put(self, request, property_id=None, format=None):
    _property = get_object_or_404(Property, id=property_id)
    serializer = self.serializer_class(data=request.data, partial=True)
    if not serializer.is_valid():
        return Response(serializer.errors, status= status.HTTP_400_BAD_REQUEST)
    else:
        serializer.save(property=_property)
        return Response(serializer.data, status=status.HTTP_200_OK)
πŸ‘€zaidfazil

1πŸ‘

I am posting a solution of associating multiple images to property. This one is a working code but the code need much more attention. Please feel free to make the following code better.

class GallerySerializer(serializers.ModelSerializer):
    class Meta:
        model = Gallery
        fields=('id', 'caption', 'image', )

    def perform_create(self, serializer):
        print ('serializer', serializer)
        serializer.save(property_instance_id=serializer.validated_data['property_id']) #property_instance_id is because i have changed the name property to property_instance in Gallery model as property is the reserved keyword

class PropertyGallery(APIView):
    serializer_class = GallerySerializer
    parser_classes = (FormParser, MultiPartParser, )
    def put(self, request, property_id=None, format=None):
        serializer = self.serializer_class(data=request.data, partial=True)
        if not serializer.is_valid():
            return Response(serializer.errors, status= status.HTTP_400_BAD_REQUEST)
        else:
            serializer.save(property_instance_id=property_id)
            return Response(serializer.data, status= status.HTTP_200_OK)
πŸ‘€Serenity

Leave a comment