上传多个图像并关联到属性

时间:2017-07-01 09:12:44

标签: python django django-rest-framework

我正在使用django rest框架来休息api。我正在尝试处理多个图像上传并将这些多个图像关联到属性。但是我的浏览器api没有显示上传图像的形式,所以我可以测试我的代码是否有效。如何上传多个图像并将它们关联到属性?

class Property(models.Model):
  owner = models.ForeignKey(settings.AUTH_USER_MODEL)
  address = models.CharField(_('Address'), max_length=140)
  rooms = models.PositiveSmallIntegerField(_('Rooms'))

class Gallery(models.Model):
    property = models.ForeignKey(Property, related_name="gallery")
    caption = models.CharField(null=True, blank=True, max_length=80)
    image = models.ImageField(upload_to="properties/rooms/")

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

class PropertySerializer(serializers.ModelSerializer, EagerLoadingMixin):
    _SELECT_RELATED_FIELDS = ['owner', ]
    _PREFETCH_RELATED_FIELDS = ['property_type',]
    gallery = GallerySerializer(many=True)


class PropertyGallery(APIView):
    serializer_class = GallerySerializer
    parser_classes = (FileUploadParser,)
    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()
            return Response(serializer.data, status=status.HTTP_200_OK)

url(r'^upload/images/(?P<property_id>[0-9]*)/$', views.PropertyGallery.as_view(), name='property-gallery'),

enter image description here

2 个答案:

答案 0 :(得分:1)

如果删除该行,

parser_classes = (FileUploadParser,)

将显示序列化器字段。

由于您编写了一个更新现有对象的视图,因此如果某个对象不存在具有特定ID,则可能需要引发异常。您可以使用快捷键函数get_object_or_404()

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)

答案 1 :(得分:1)

我发布了一个将多个图像与属性相关联的解决方案。这是一个工作代码,但代码需要更多的关注。请随意更好地制作以下代码。

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)