如何向用户提供django-webodt文件?

时间:2013-08-21 02:34:29

标签: django

我正在尝试允许用户导出一些数据库数据。我正在使用django-webodt从他们的数据创建一个.odt文件。然后我试图允许他们下载它。文件创建得很好,但下载时似乎下载了一个空白文件。我认为服务器查找文件的位置和实际位置之间存在一些差异。我想知道如何让它正常工作?我对django比较新,所以任何帮助都会受到赞赏。我的代码如下:

def downloadBook(request, val):
    template = webodt.ODFTemplate('conversion.odt')
    context = dict(ideas=Book.objects.getIdeaSet(int(val)))
    document = template.render(Context(context))
    file_name = os.path.basename(document.name)
    path_to_file = os.path.dirname(document.name)
    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
    response['X-Sendfile'] = smart_str(path_to_file)
    return response

1 个答案:

答案 0 :(得分:0)

我做了以下工作并且有效:

from django.template import Context
from webodt import ODFTemplate

template = ODFTemplate('template_file.odt')
context = { 'some_dict': '' }
document = template.render(Context(context))
response = HttpResponse(document.read(), mimetype='application/vnd.oasis.opendocument.text')
response['Content-Disposition'] = "attachment; filename=fancy-filename-as-you-like.odt"
document.close() # delete the document on /tmp
return response