[Answer]-How can i make the common function/view for servinf downloadble files in django python

1👍

What would you like to do is get actual file path from object. And as you have said the file path is stored in object.path that makes it easy.

For example:

urls.py

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

In 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
👤Rohan

Leave a comment