0

オブジェクトのリストを html テーブルに表示しています。リンクされたファイルをダウンロードしてもらいたいすべての行の前にダウンロードリンクがあります。

私はこの機能を作りました

def make_downloadable_link(path):
    #Prepare the form for downloading
    wrapper      = FileWrapper(open(mypath))
    response     = HttpResponse(wrapper,'application/pdf')
    response['Content-Length']      = os.path.getsize(mypath)  
    fname = mypath.split('/')[-1]  
    response['Content-Disposition'] = 'attachment; filename= fname'
    return response

単一ファイルのビューでハードコードされたパスに使用すると、これは正常に機能します。しかし、テーブル内のすべてのファイルで機能するように汎用ビューを作成したい

変数で利用可能なファイルのパスを持っていobject.pathますが、パスオブジェクトをダウンロードしたファイルビューに渡す方法がわかりません。その実際のパスをユーザーから隠したいからです。

そのダウンロードファイルビューの URLs.py ファイルに何を書けばいいのかわからない

4

1 に答える 1

1

やりたいことは、オブジェクトから実際のファイル パスを取得することです。そして、あなたが言ったように、ファイルパスが保存されobject.pathているので簡単です。

例えば:

urls.py

url(r'^download/(?P<object_id>\d+)/$', "yourapp.views.make_downloadable_link", name="downloadable")

views.py で:

def make_downloadable_link(object_id):

    # get object from object_id
    object = ObjectModel.objects.get(id=object_id)
    mypath = object.path

    #prepare to serve the file
    wrapper      = FileWrapper(open(mypath))
    response     = HttpResponse(wrapper,'application/pdf')
    response['Content-Length']      = os.path.getsize(mypath)  
    fname = mypath.split('/')[-1]  
    response['Content-Disposition'] = 'attachment; filename= fname'
    return response
于 2012-12-03T06:01:55.753 に答える