Reputation: 443
I would like to automatically save the result in a pdf file in a chosen directory. I use the django-hardcopy module. Currently, I can display the pdf with a url. Thank you for your ideas.
Here is the view:
from django.conf import settings
from hardcopy.views import PDFViewMixin, PNGViewMixin
class pdf_hardcopy(PDFViewMixin, TemplateView):
download_attachment = True
template_name = 'project/pdf_hardcopy.html'
def get_filename(self):
return "my_file.pdf"
def get_context_data(self, *args, **kwargs):
context = super(pdf_hardcopy, self).get_context_data(*args, **kwargs)
id = self.kwargs['pk']
dossier_media = str(settings.MEDIA_ROOT)
GetDataTeam = Datas.objects.filter(id=id)
context["GetDataTeam"] = GetDataTeam
return context
My url:
path('pdf_hardcopy/<int:pk>/', views.pdf_hardcopy.as_view(), name='pdf_hardcopy'),
Upvotes: 1
Views: 485
Reputation: 2000
Taking a quick look at the repo, it doesn't look like there's any built-in way to do this. I would probably override PDFViewMixin
's get_file_response
method. You can see the current implementation in the views.py
file [github link].
You could do something like this in your views.py file:
class PDFViewAndSaveMixin(PDFViewMixin):
"""Override PDFViewMixin to also save file."""
def get_file_response(self, content, output_file, extra_args):
with open(f'save/location/{self.get_filename}', ‘w’) as local_file:
local_file.write(output_file)
return super().get_file_response(content, output_file, extra_args)
class pdf_hardcopy(PDFViewAndSaveMixin, TemplateView):
# ...
This is a rather crude way of saving the file, and you probably should create a Django model with a FileField to manage these files, rather than simply writing them directly to disk. See the Django docs on managing files.
Upvotes: 1