使用文件上传测试视图时出错

Error when testing the view with a file upload

我想使用以下函数从我的视图中测试文件上传:

def test_post(self):
    with open("path/to/myfile/test_file.txt") as file:
        post_data = {
            'description': "Some important file",
            'file': file,
        }
        response = self.client.post(self.test_url, post_data)
        self.assertEqual(response.status_code, 302)

        document = Document.objects.first()
        self.assertEqual(document.description, "My File")
        self.assertEqual(document.filename, 'test_file.txt')

当我在实际网站上测试文件上传时,它有效。但是当我 运行 这个测试时,我得到以下错误:

django.core.exceptions.SuspiciousFileOperation: Storage can not find an available filename for "WHJpMYuGGCMdSKFruieo/Documents/eWEjGvEojETTghSVCijsaCINZVxTvzpXNRBvmpjOrYvKAKCjYu/test_file_KTEMuQa.txt". Please make sure that the corresponding file field allows sufficient "max_length".

这是我的表格save方法:

def save(self, commit=True):
    instance = super(DocumentForm, self).save(commit=False)
    instance.filename = self.cleaned_data['file'].name
    if commit:
        instance.save()  # error occurs here
    return instance

在实际网站上运行,我怀疑这与我在测试中设置文件的方式有关;可能是小东西。

为了简洁起见,我从原来的问题中删除了不相关的模型字段。但是当 Ahtisham 请求查看 upload_to 属性(它有一个自定义函数)时,我删除了那些不相关的字段并且它起作用了!

所以这是我的原始代码(没有用),其中包含不相关的字段:

def documents_path(instance, filename):
    grant = instance.grant  
    client = grant.client
    return '{0}/Grant Documents/{1}/{2}'.format(client.folder_name, grant.name, filename)

....

file = models.FileField(upload_to=documents_path)

但这行得通:

def documents_path(instance, filename):
   return 'Documents/{0}'.format(filename)

它在实际网站上运行的原因是因为它没有使用测试装置中的长字符。看来那些我认为与问题无关的字段实际上非常重要!

TL;DR 我减少了自定义文档路径的长度。

我在使用 ImageField 时遇到了同样的错误。解决方案是在 models.py 中添加 max_length=255:

image = models.ImageField(upload_to=user_path, max_length=255)

然后 运行 python manage.py makemigrationspython manage.py migrate.