I want to create an admin action to download users pdf files The user file would be uploaded in the media directory What and the admin should be able to download any file I tried using pdfkit to let him download the files but I couldn't
> import pdfkit
>
> def downloadCV(self, request, queryset):
> projectUrl = str(queryset[0].cv)+''
> pdf = pdfkit.from_url(projectUrl, False)
> response = HttpResponse(pdf,content_type='application/pdf')
> response['Content-Disposition'] = 'attachment; filename="user_cv.pdf"'
So my question is what is the best way to let the admin dowload pdf files
I tried this way
def downloadCV(self, request, queryset):
for x in queryset:
projectUrl = str(x.cv)+''
if projectUrl:
with open(projectUrl, 'r') as pdf:
response = HttpResponse(pdf,content_type='application/pdf')
response['ContentDisposition']='attachment;filename="user_cv.pdf"'
return response
pdf.closed
but I can only download one file at atime is there is away to download multiples pdfs at once ?
A request can only give one response. So i think you have 2 options
Option 1, You could make multiple requests. Basically similar to the code you have now but targeting one file but with some kind of javascript code that will run the action on an individual file in a new tab/window. So say you checked off 3 files in the admin and ran the action it would need to open 3 tabs each one its own file serving you the pdf.
Option 2, Zip up the files and return that one zip file instead. This seems easier to me. Here is an example that I haven't tested but you get the idea.. gather the files together from the queryset then shove them in a zipfile and then serve up the zipfile.
import pdfkit
import tempfile
import zipfile
def downloadCV(self, request, queryset):
with tempfile.SpooledTemporaryFile() as tmp:
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive:
for index, item in enumerate(queryset):
projectUrl = str(item.cv) + ''
fileNameInZip = '%s.zip' % index
pdf = pdfkit.from_url(projectUrl, False)
archive.writestr(fileNameInZip, pdf)
tmp.seek(0)
response = HttpResponse(tmp.read(), mimetype='application/x-zip-compressed')
response['Content-Disposition'] = 'attachment; filename="pdfs.zip"'
return response
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With