django-wkhtmltopdf icon indicating copy to clipboard operation
django-wkhtmltopdf copied to clipboard

How to use with generic class based views? or provide class mixin

Open luzfcb opened this issue 9 years ago • 3 comments

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

luzfcb avatar Sep 18 '15 14:09 luzfcb

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.

johnraz avatar Feb 17 '16 20:02 johnraz

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.

Gwildor avatar Feb 18 '16 11:02 Gwildor

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

colinkingswood avatar Jun 13 '17 11:06 colinkingswood