简体   繁体   English

如何在Django中设置文件的动态路径

[英]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. 我正在研究一个项目,用户(客户)可以登录并可以查看有关其发票的信息,也可以下载(以Pdf格式)等。

When User setted up in admin panel, his pdf files is uploaded ( User can have many Pdf files ) 当用户在管理面板中设置后,他的pdf文件就会上传(用户可以有很多Pdf文件)

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. 当Pdfs上传时,一个函数会基于他的id创建文件夹,并将其放入,因此我必须创建一个dynamicaly函数,当用户单击它时,它将下载正确的pdf文件。

This is a for in html that prints all "charges" to user: 这是html中的for,它向用户显示所有“费用”:

{% for 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 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. 甚至我尝试创建一个可以动态设置路径并将其转换为字符串的函数django告诉我,它期望使用字符串而不是函数。

def DownloadPdf(request, charge_id):                                                                                                                            

with open(os.path.join(settings.MEDIA_ROOT,models.Charge.upload_pdf.url, 'rb') as fh:     
    response = HttpResponse(fh.read(), 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. 我想将所选pdf格式的网址插入ID。 But i donw know how to pull out the url and link it with the other media path and use corrrectly the id. 但是我不知道如何拉出URL并将其与其他媒体路径链接并正确使用ID。

edit 编辑

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. 反向使用参数'('/media/user_4/invoice-alex-1.pdf')和参数'{}'的'download_pdf'。 1 pattern(s) tried: ['download/(?P\\d+)/$'] 尝试了1种模式:['download /(?P \\ d +)/ $']

You need not write a view to handle the download part. 您无需编写视图即可处理下载部分。 Browsers today are smart enough to handle the download part. 当今的浏览器足够聪明,可以处理下载部分。 In your template, just do the following (assuming that at template level your are aware who is user and what sort of file is to be downloaded for him. Just pass all this info in the context of the view where the user will have the authority to download stuff.): 在您的模板中,只需执行以下操作(假设在模板级别上您知道谁是用户,以及将为他下载哪种文件。只需在用户将拥有权限的视图上下文中传递所有这些信息下载内容。):

<a href="{{MEDIA_URL}}<your_file_with_id.pdf>">Download File</a>

And that's it. 就是这样。 The browser will automatically download the file. 浏览器将自动下载文件。 You need not do anything else. 您无需执行其他任何操作。

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):

try:
    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM