2013-08-21 12 views
0

我試圖讓用戶導出他們的一些數據庫數據。我正在使用django-webodt從他們的數據創建一個.odt文件。然後我試圖讓他們下載它。該文件創建得很好,但下載時似乎下載了一個空白文件。我認爲服務器在查找文件的位置和實際位置之間有一些區別。我想知道如何讓這個工作正常?我對django比較新,所以任何幫助將不勝感激。我的代碼如下:如何向用戶提供django-webodt文件?

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 
+0

我認爲正確的MIME類型是application/vnd.oasis.opendocument.text –

+0

是您的查詢輸入有誤?不應該是context = dict(ideas = Book.objects.get(IdeaSet = int(val))) – Ulmer

+0

Ulmer,查詢很好,並且獲得正確的數據。我正在使用一個管理器並定義了一個函數getIdeaSet。 – user2701944

回答

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