Django REST Framework图片上传 [英] Django REST Framework image upload
本文介绍了Django REST Framework图片上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有模型产品:
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
)
...
然后我有了序列化器:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = (
...
'image',
...
)
然后我有意见:
class ProductViewSet(BaseViewSet, viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
如何使用Postman上传图像?将图片上传到模型的最佳做法是什么?谢谢。
How I can upload image with Postman? What is the best practices to upload image to model? Thank you.
推荐答案
您可以创建用于上传图像的单独端点,就像这样:
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, ....)
您可以解决该问题
-更新:
就是这样从邮递员
-- update: this's how to upload from postman
这篇关于Django REST Framework图片上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文