尝试发帖时未提交任何文件。 Django Rest 框架

问题描述 投票:0回答:1

我正在尝试发送“POST”,但问题是我收到“未提交文件错误”,我不知道为什么。

在我的models.py

我的个人详细信息

中没有“图标”

个人资料样本

class PersonalDetailSample(models.Model): 
    ...
    icon = models.FileField(_('icon'), db_index=True, null=True, blank=True, upload_to='files/')
    ...

序列化器.py

class PersonalDetailSerializer(serializers.ModelSerializer):
    ...
    icon = serializers.FileField(source='details_sample.icon')
    ...

    class Meta:
        model = PersonalDetail
        fields = (
            ..., 'icon', ...
        )

在我的views.py

def perform_create(self, serializer):
    preview_text, preview_name = personal_details.find_text_name(serializer.validated_data)
    serializer.save(user_id=self.request.user,
                    details_sample=serializer.validated_data['details_sample'],
                    content=serializer.validated_data['content'],
                    preview_name=preview_name)

我想做的帖子:

{
    "checked":true,
    "content": {
        "text_field_1": {
            "size":"small",
            "text":"My userdefined Title",
            "title":"Title"
        },
        "text_field_2": {
            "size":"big",
            "text":"I don't have inspiration",
            "title":"Nachricht"
        }
    },
    "details_sample":27,
    "preview_user_title": "This is my User Title"
}

我收到此错误:(400 错误请求)

{ “图标”: [ “没有提交任何文件。” ] }

我也不知道为什么...

也许有人也有同样的烦恼。

python django django-rest-framework
1个回答
7
投票

尝试在序列化器上使用 required=False ,或者如果您根本不需要使用其余 api 在文件上写入,请使用 read_only=True 。

required=False 选项http://www.django-rest-framework.org/api-guide/fields/#required

class PersonalDetailSerializer(serializers.ModelSerializer):
    ...
    icon = serializers.FileField(source='details_sample.icon', required=False)
    ...

    class Meta:
        model = PersonalDetail
        fields = (
            ..., 'icon', ...
        )

或只读选项 http://www.django-rest-framework.org/api-guide/fields/#read_only

class PersonalDetailSerializer(serializers.ModelSerializer):
    ...
    icon = serializers.FileField(source='details_sample.icon', read_only=True)
    ...

    class Meta:
        model = PersonalDetail
        fields = (
            ..., 'icon', ...
        )
© www.soinside.com 2019 - 2024. All rights reserved.