首页 > 解决方案 > 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)

标签: djangodjango-rest-framework

解决方案


推荐阅读