django rest 上传多张图片
django rest upload multiple images
我正在使用 Django 休息框架开发电子商务 API
所以我希望当用户添加新产品时他可以上传多张图片
我怎样才能用休息框架做到这一点?
这是我的模型、视图、序列化器
我的models.py
class Product(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
description = models.TextField(null=True, blank=True)
owner = models.ForeignKey(User, related_name='Products', on_delete=models.CASCADE,null=True)
class ProductImages(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
images = models.FileField(upload_to='API/images',max_length=100,null=True)
我的序列化程序
class ProductImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProductImages
fields = '__all__'
class Productserializer(serializers.ModelSerializer) :
images= ProductImageSerializer(many=True)
class Meta:
model = Product
fields = ('id','title','price','description','whatfor','categories','size','rooms','Location','Lat','Long','owner_id','images')
extra_kwargs = {"user":{"read_only":True}}
def validate(self, attrs):
attrs['owner'] = self.context.get("request").user
return attrs
我的看法
class ProductViewSet(ModelViewSet):
queryset = Product.objects.all()
serializer_class = Productserializer
filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
filterset_class = ProductFilter
search_fields = ['title', 'description']
ordering_fields = ['price', 'last_update']
def get_serializer_context(self):
return {'request': self.request}
我觉得要实现多次上传,需要在ProductSerializer
中设置上传的附加字段。
class Productserializer(serializers.ModelSerializer) :
images= ProductImageSerializer(many=True, read_only = True)
uploaded_images = serializers.ListField(
child = serializers.FileFiled(max_length = 1000000, allow_empty_file = False, use_url = False)
write_only = True
)
class Meta:
model = Product
fields = ('id', ...,'images', 'uploaded_images', ) # add the field
extra_kwargs = {"user":{"read_only":True}}
def create(self, validated_data):
uploaded_data = validated_data.pop('uploaded_images')
new_product = Product.objects.create(**validated_data)
for uploaded_item in uploaded_data:
new_product_image = ProductImages.objects.create(product = new_product, images = uploaded_item)
return new_product
并且在前端,您需要将键 images
更改为 uploaded_images
。
比如像下面这样。
const formData = new FormData();
event.target.files.forEach((image) => {
formData.append('uploaded_images', image);
});
我正在使用 Django 休息框架开发电子商务 API 所以我希望当用户添加新产品时他可以上传多张图片 我怎样才能用休息框架做到这一点? 这是我的模型、视图、序列化器
我的models.py
class Product(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
description = models.TextField(null=True, blank=True)
owner = models.ForeignKey(User, related_name='Products', on_delete=models.CASCADE,null=True)
class ProductImages(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
images = models.FileField(upload_to='API/images',max_length=100,null=True)
我的序列化程序
class ProductImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProductImages
fields = '__all__'
class Productserializer(serializers.ModelSerializer) :
images= ProductImageSerializer(many=True)
class Meta:
model = Product
fields = ('id','title','price','description','whatfor','categories','size','rooms','Location','Lat','Long','owner_id','images')
extra_kwargs = {"user":{"read_only":True}}
def validate(self, attrs):
attrs['owner'] = self.context.get("request").user
return attrs
我的看法
class ProductViewSet(ModelViewSet):
queryset = Product.objects.all()
serializer_class = Productserializer
filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
filterset_class = ProductFilter
search_fields = ['title', 'description']
ordering_fields = ['price', 'last_update']
def get_serializer_context(self):
return {'request': self.request}
我觉得要实现多次上传,需要在ProductSerializer
中设置上传的附加字段。
class Productserializer(serializers.ModelSerializer) :
images= ProductImageSerializer(many=True, read_only = True)
uploaded_images = serializers.ListField(
child = serializers.FileFiled(max_length = 1000000, allow_empty_file = False, use_url = False)
write_only = True
)
class Meta:
model = Product
fields = ('id', ...,'images', 'uploaded_images', ) # add the field
extra_kwargs = {"user":{"read_only":True}}
def create(self, validated_data):
uploaded_data = validated_data.pop('uploaded_images')
new_product = Product.objects.create(**validated_data)
for uploaded_item in uploaded_data:
new_product_image = ProductImages.objects.create(product = new_product, images = uploaded_item)
return new_product
并且在前端,您需要将键 images
更改为 uploaded_images
。
比如像下面这样。
const formData = new FormData();
event.target.files.forEach((image) => {
formData.append('uploaded_images', image);
});