django - non_field_errors": ["无效数据。需要一本字典,但得到了 InMemoryUploadedFile。"]
问题描述
从邮递员创建数据时,它显示此错误,“image”:“non_field_errors”:“无效数据。需要字典,但得到了 InMemoryUploadedFile。”
以及如何通过 ModelViewSet 一次性上传多张图片
class ProductViewSet(ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
lookup_field = 'slug'
parser_classes = [MultiPartParser, FormParser]
class ProductImageSerializer(ModelSerializer):
class Meta:
model = ProductImage
fields = ['id', 'image']
class ProductSerializer(ModelSerializer):
image = ProductImageSerializer(required=True, many=True)
class Meta:
model = Product
fields = '__all__'
def create(self, validated_data):
product = Product.objects.create(**validated_data)
image_data = validated_data.pop('image')
if image_data.is_valid():
for img in image_data:
image = ProductImage.objects.create(product=product, image=img)
product.save()
return product
class Product(Core):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='product')
brand = models.ForeignKey(Brand, on_delete=models.RESTRICT, related_name='product')
name = models.CharField(
_('Product Name'),
max_length=255,
validators=[
MinLengthValidator(30),
MaxLengthValidator(255),
],
help_text=_('Title should be Minimum 30 Characters'),
)
slug = models.SlugField(unique=True, blank=True)
is_active = models.BooleanField(default=True)
is_approved = models.BooleanField(default=False)
class ProductImage(Core):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='image')
image = models.ImageField(upload_to=path_and_rename)
解决方案
推荐阅读
- python - 如何让 django 找到 Sphinx 的特定 css 文件?
- winapi - 使用 Autohotkey 读取 StdErr 和 StdOut
- c# - 如何使对象“看起来”到对象
- reactjs - 在基于 Web 浏览器的客户端上存储授权(或 JWT)令牌的位置?
- haskell - 战舰游戏 - Haskell
- php - (JSON 文件)Wamp 中是否有任何功能可以使其正常工作?
- node.js - 无服务器框架 - 部署多个 AWS 云端分发
- java - 如何为 html 文件正确创建这些方法?
- css - 图像未覆盖弹性项目内的整个区域
- assembly - 装配 ARM - 分段错误