python - How to set dynamic path to a file in django -


i working on project user (customer) can login , can view information invoices, download them ( in pdf format ) etc.

when user setted in admin panel, pdf files uploaded ( user can have many pdf files )

when pdfs uploaded, function create folders based on id, , put them in, have create dynamicaly function downloads correct pdf file when user click on it.

this in html prints "charges" user:

{% printforme in print_user_charges %}         <tr>           <td>{{ printforme.invoice_number }}</td>           <td>{{ printforme.price }} €</td>           <td>{{  printforme.reason }}</td>           <td>{{ printforme.customer }} {{ printforme.customer.surname }}</td>           <td>{{ printforme.charge_date }}</td>           <td>  <a href="{% url 'download_pdf' printforme.id %}"> download </a></td>  {% endif %} 

even try create function sets path dynamicaly , converting string django tells me expects string , not function.

def downloadpdf(request, charge_id):                                                                                                                              open(os.path.join(settings.media_root,models.charge.upload_pdf.url, 'rb') fh:          response = httpresponse(fh.read(), content_type="application/pdf")        response['content-disposition'] = 'filename=invoice.pdf'                  return response                                                       

i want insert url of selected pdf base id. donw know how pull out url , link other media path , use corrrectly id.

edit

if change this:

    url(r'^download/(?p<charge_id>\d+)/$', views.downloadpdf, name='download_pdf'), 

and this:

with open(os.path.join(settings.media_root, charge_id), 'rb') 

it gives me error:

reverse 'download_pdf' arguments '('/media/user_4/invoice-alex-1.pdf',)' , keyword arguments '{}' not found. 1 pattern(s) tried: ['download/(?p\d+)/$']

you need not write view handle download part. browsers today smart enough handle download part. in template, following (assuming @ template level aware user , sort of file downloaded him. pass info in context of view user have authority download stuff.):

<a href="{{media_url}}<your_file_with_id.pdf>">download file</a> 

and that's it. browser automatically download file. need not else.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -