Vaios Lk Vaios Lk - 11 months ago 83
Python Question

How to set dynamic path to a file in django

I working on a project that User (customer) can login and can view information about his invoices, download them ( in Pdf format ) etc.

When User setted up in admin panel, his pdf files is uploaded ( User can have many Pdf files )

When Pdfs is uploaded, a function create folders based on his id, and put them in, so i have to create a dynamicaly function that downloads the correct pdf file when User click on it.

This is a for in html that prints all "charges" to user:

{% for printforme in print_user_charges %}
<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' %}"> Download </a></td>

{% endif %}

Even i try to create a function that sets the path dynamicaly and converting it to a string django tells me that expects a string and not a function.

def DownloadPdf(request, charge_id):

with open(os.path.join(settings.MEDIA_ROOT,models.Charge.upload_pdf.url, 'rb') as fh:
response = HttpResponse(, content_type="application/pdf")
response['Content-Disposition'] = 'filename=invoice.pdf'
return response

I want to insert the url of the selected pdf base to the id. But i donw know how to pull out the url and link it with the other media path and use corrrectly the id.


if i change to 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 that error:

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

Answer Source

After all i find a working solution

My main problem it was that i was try to get an instance and i do not pass it into any variable before i try to load the file. I change the open method to, i found the last one more clear.

def DownloadPdf(request, charges_id):

    invoice = Charge.objects.get(pk=charges_id)
except Charge.DoesNotExist:
    raise Http404

response = HttpResponse(File(invoice.upload_pdf), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"'
return response