django-wkhtmltopdf
django-wkhtmltopdf copied to clipboard
How to use with generic class based views? or provide class mixin
Is there any way to use this library together with other class-based views like
using a hypothetical class called PDFRenderMixin
class FooDetailView(PDFRenderMixin, generic.DetailView):
model = Foo
template_name = 'foo/foo_detail.html'
pdf_template_name = 'foo/foo_html_to_pdf_content_template.html'
pdf_header_template_name = 'foo/foo_html_to_pdf_header_template.html'
pdf_footer_template_name = 'foo/foo_html_to_pdf_footer_template.html'
pdf_filename = 'foo_file.pdf'
pdf_show_content_in_browser = True
I'd say that it should work by doing something like:
class FooDetailView(PDFTemplateView, generic.DetailView):
pass
Did you experience failure of any kind, sorry but I need a bit more to be able to help further here.
I've used the view like this:
class ResultsPDFView(PDFTemplateView, ResultsView):
...
Where ResultsView
is a subclass of generic.TemplateView
, and this worked fine! One tiny annoyance I had is that I had to reset template_name
(which I had set on ResultsView
), because PDFTemplateView
sets it as well. One tiny improvement might be to not set it on PDFTemplateView
at all (its parent, generic.TemplateView
, sets it anyway) and let Python's MRO figure it out, which in my case would picked it up from ResultsView
instead of PDFTemplateView
's parent.
In case it helps anyone, I converted a Detail View to work with this using the single object mixin , the get method copied from PDFTemplateView:
original Detail View:
class ResumePrintHtmlView(DetailView):
model = Graduate
template_name = 'jobsite/print/graduate_resume.html'
PDF version:
class ResumePrintPdfView(SingleObjectMixin, PDFTemplateView):
model = Graduate
template_name = 'jobsite/print/graduate_resume.html'
def get(self, request, *args, **kwargs):
self.object = self.get_object()
context = self.get_context_data(object=self.object)
response_class = self.response_class
try:
if request.GET.get('as', '') == 'html':
# Use the html_response_class if HTML was requested.
self.response_class = self.html_response_class
return super(PDFTemplateView, self).get(request,
*args, **kwargs)
finally:
# Remove self.response_class
self.response_class = response_class