6

ユーザーがリンクをクリックしたときにブラウザーで開くのではなく、プロジェクト ディレクトリ内の PDF ファイルをダウンロードできるようにしたいと考えています。

この質問に従いました Djangoでダウンロードするファイルを生成しています

しかし、私はエラーが発生しています:

Exception Type: SyntaxError
Exception Value: can't assign to literal (views.py, line 119)
Exception Location: /usr/local/lib/python2.7/dist-packages/django/utils/importlib.py in import_module, line 35

ダウンロードリンクを作成しました:

 <a href="/files/pdf/resume.pdf" target="_blank" class="btn btn-success btn-download" id="download" >Download PDF</a>

urls.py:

url(r'^files/pdf/(?P<filename>\{w{40})/$', 'github.views.pdf_download'),

ビュー.py:

def pdf_download(request, filename):
    path = os.expanduser('~/files/pdf/')
    f = open(path+filename, "r")
    response = HttpResponse(FileWrapper(f), content_type='application/pdf')
    response = ['Content-Disposition'] = 'attachment; filename=resume.pdf'
    f.close()
    return response

エラー行は次のとおりです。

response = ['Content-Disposition'] = 'attachment; filename=resume.pdf'

ダウンロードできるようにするにはどうすればよいですか?

ありがとう!

アップデート

Firefox では動作しますが、Chrome v21.0 では動作しません。

4

2 に答える 2

8

次のコードを使用すると、ファイルを新しいページで開く代わりにダウンロードする必要があります

def pdf_download(request, filename):
  path = os.expanduser('~/files/pdf/')
  wrapper = FileWrapper(file(filename,'rb'))
  response = HttpResponse(wrapper, content_type=mimetypes.guess_type(filename)[0])
  response['Content-Length'] = os.path.getsize(filename)
  response['Content-Disposition'] = "attachment; filename=" + filename
  return response
于 2013-02-01T11:48:01.360 に答える
5

その行に余分な=ものがあるため、構文が無効になります。そのはず

response['Content-Disposition'] = 'attachment; filename=resume.pdf'

=(2 つあるからといって必ずしも無効になるわけではないことに注意してください:foo = bar = 'hello'は完全に有効ですが、その場合、左と中間の両方の用語が名前です。あなたのバージョンでは、中間の用語はリテラルであり、代入できません。 )

于 2012-08-06T14:35:11.220 に答える