我想跟踪文件被下载的次数。我是这样看的:
1) 而不是<a href="{{ file.url }}" download>...</a>
,我应该将用户重定向到 download
看法; <a href="download/{{ file.id }}/{{ file.name }}">...</a>
file.id
andfile.name
needed for proper work of function bellow.
2) 在我的 download
中查看我需要注册特定文件的下载,假设我有 registrate_dl
完成其工作的函数。另外,我需要接受{{ file.url }}
值如第一段的第一个链接中所示。
3)最后,我注册了特定文件的下载并得到了 {{ file.url }}
如file_url
多变的。
但是,如果,在 view
的末尾我放置的功能return redirect(file_url)
,它只是将我重定向到文件,而不开始下载。
file_url
,并触发下载?
最佳答案
您可以将文件作为响应的一部分返回。如何操作取决于确切的文件类型,但这里是我在另一个答案中使用的 CSV 示例。
def csv_view(request):
filename = "Your filename"
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="{}.csv"',format(filename)
writer = csv.writer(response)
writer.writerow("Some stuff")
messages.success(request, 'Consultation added to report successfully!')
messages.warning(request, 'Note: Certain needs may not appear in report, \
this is a result of filtering process.')
return response
关于python - 重定向到下载 Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58190415/