我的django 1.6有问题。我试图通过FileField模型保存文件,然后再次打开它以将其提供给浏览器。尝试打开已保存的文件时,我无法访问该文件,因此无法获取“无类型”文件。错误。
这就是我的代码的制作方式:
class WB(models.Model):
odt = models.FileField()
def save(request):
...
#tmp.odt is generated befor
tmp = File(open('files/tmp/tmp.odt', 'rb'))
wb.odt.save("test.odt", tmp)
tmp.close()
...
def display(request):
odt = wb.odt.open(mode='rb')
response = HttpResponse(content_type='application/vnd.oasis.opendocument.text; charset=UTF-8')
response['Content-Disposition'] = 'attachment; filename='test.odt'
#in the next line the error is thrown
response['Content-Length'] = os.path.getsize(odt.url)
response['Content-Transfer-Encoding'] = 'binary'
response.write(odt)
return response
File "D:\python2.7\lib\site-packages\django-1.6.7-py2.7.egg\django\core\handlers\base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\workspace\certwb\wb\views.py" in display
25. response['Content-Length'] = os.path.getsize(odt.url)
Exception Type: AttributeError at /display/
Exception Value: 'NoneType' object has no attribute 'url'
答案 0 :(得分:0)
尝试wb.odt.save("test.odt", tmp, save=False)
,当save=True
(默认设置)时,您也会在保存文件后保存模型,这可能不是您想要的。
答案 1 :(得分:0)
最后我得到了它的工作:D
好像我不需要打开文件,因为它在访问模型时已经打开了。因此,将我的视图更改为以下内容解决了问题:D
def: display(request):
odt = wb.odt.file
response = HttpResponse(content_type='application/vnd.oasis.opendocument.text; charset=UTF-8')
response['Content-Disposition'] = 'attachment; filename="test.odt"'
response['Content-Length'] = odt.size
response['Content-Transfer-Encoding'] = 'binary'
response.write(odt.read())
return response