Django REST Framework image upload

前端 未结 2 1669
离开以前
离开以前 2020-12-15 05:41

I have model Product:

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

class Product(models.Model):         


        
2条回答
  •  粉色の甜心
    2020-12-15 06:25

    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

提交回复
热议问题