DRF试图保存图像时出现错误“提交的数据不是文件”

2024-06-26 13:53:21 发布

您现在位置:Python中文网/ 问答频道 /正文

这是Django REST框架项目。我正在尝试创建一个包含图像的新产品。我在模型中使用了FileField作为图像。我用POST方法把数据发送到服务器。您可以看到下面的请求。您可以看到发送的图像是一个文件,但是为什么它不保存并给出错误400:{image: ["The submitted data was not a file. Check the encoding type on the form."]}?我也试过enctype="multipart/form-data",但没有区别。在

{
    full_description:"<p>asdasdasd</p>"
    image:File(2835) {
        name: "php.png", lastModified: 1520497841095, 
        lastModifiedDate: Thu Mar 08 2018 12:00:41 GMT+0330 (+0330), 
        webkitRelativePath: "", size: 2835, …}
    mini_description:"dasdasdasd"
    price:"222"
    title:"asdsadasds"
    video_length:"233"
    video_level:"pro"
    you_learn:"asdasdasd"
    you_need:"asdasdasd"
}

服务器说:

^{pr2}$

我的观点:

^{3}$

相关型号系列化剂:

# product
class ProductSerializer(ModelSerializer):
    product_ratings = ProductRatingsSerializer(many=True, read_only=True)
    product_video = ProductVideoSerializer(many=True, read_only=True)
    author = serializers.SerializerMethodField()

    def get_author(self, obj):
        return obj.author.first_name + ' ' + obj.author.last_name

    def get_category(self, obj):
        return obj.category.title

    class Meta:
        model = Product
        fields = [
            'product_id',
            'author',
            'title',
            'mini_description',
            'you_learn',
            'you_need',
            'full_description',
            'price',
            'discount',
            'discount_code',
            'discount_code_precent',
            'video_level',
            'video_length',
            'created_date',
            'updated_date',
            'product_ratings',
            'product_video',
            'image'
        ]
        read_only_fields = ['product_id', 'created_date', 'updated_date', 'author',
                            'product_ratings']

    def get_image(self, obj):
        request = self.context.get('request')
        return request.build_absolute_uri(obj.image.url)

Tags: name图像imageselfyoutrueobjget