如何在Django REST Fram中测试FileField

2024-09-28 17:01:26 发布

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

我有一个序列化程序,我正在测试:

class AttachmentSerializer(CustomModelSerializer):
    order = serializers.PrimaryKeyRelatedField()
    file = FileField()

    class Meta:
        model = Attachment
        fields = (
            'id',
            'order',
            'name',
            'file_type',
            'file',
            'created_at',
        )

我的测试只是检查它是否有效:

^{pr2}$

我经常犯这样的错误:

{'file': ['No file was submitted. Check the encoding type on the form.']}

我尝试用很多不同的方法创建一个文件,比如用StringIO/BytesIO,file等等,但都没有用。在

可能出了什么问题?在


Tags: the程序attachmentmodel序列化typeordermeta
3条回答
from django.core.files.uploadedfile import SimpleUploadedFile
content = SimpleUploadedFile("file.txt", "filecontentstring")
data = {'content': content}

尝试这样的smth,因为如果您检查FileField序列化程序的代码-它期望上载的文件具有名称和大小:

^{pr2}$

StringIO或打开的文件对象没有size属性。在

问题是,将打开的文件传递给APIClient/APIRequestFactory,而不是视图本身。Django请求将文件包装为^{},这是您应该使用的。在

我也遇到了类似的问题。结果发现Django REST Framework FileField不能与JSON API解析器一起使用。DRFdocumentation states“大多数解析器,例如JSON不支持文件上传。”

您的问题没有显示您配置了哪个解析器,但是考虑到JSON有多常见,它可能是罪魁祸首。您可以全面设置不同的解析器,也可以为特定的API视图设置一个不同的解析器,如here所述。在

一旦解析器问题得到解决,我就用Django文件进行了测试,但也许其他方法也可以起作用:

from django.core.files import File

def test_create(self):
    ...
    data = {
        'file': File(open(path_to_test_file, 'rb')),
    }
    ...

相关问题 更多 >