Django REST Framework image upload

2019-02-06 10:27发布

I have model Product:

def productFile(instance, filename):
    return '/'.join( ['products', str(instance.id), filename] )

class Product(models.Model):
    ...

    image = models.ImageField(
        upload_to=productFile,
        max_length=254, blank=True, null=True
    )
    ...

Then I have serializer:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = (
            ...
            'image',
            ...
        )

And then I have views:

class ProductViewSet(BaseViewSet, viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

How I can upload image with Postman? What is the best practices to upload image to model? Thank you.

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-06 11:20

you can create separate endpoint for uploading images, it would be like that:

class ProductViewSet(BaseViewSet, viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

    @detail_route(methods=['post'])
    def upload_docs(request):
        try:
            file = request.data['file']
        except KeyError:
            raise ParseError('Request has no resource file attached')
        product = Product.objects.create(image=file, ....)

you can go around that solution

-- update: this's how to upload from postman enter image description here

查看更多
登录 后发表回答