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

Recommend defaulting content_type to PDF

Open jacklinke opened this issue 2 years ago • 1 comments

This issue is somewhat selfish in nature. I prefer to use Function-Based Views, and would like to use WeasyTemplateResponse in these views with minimal boilerplate. Specifying content_type in the returned response should no longer be necessary.

As noted in the README, support for PNG output in Weasyprint has been removed, so we can default to using 'application/pdf' as the content_type for WeasyTemplateResponse.

Additionally, this can be done in an entirely backwards-compatible manner by setting the content_type in the init method of WeasyTemplateResponse, defaulting to a pdf if not otherwise set: self.content_type = kwargs.get("content_type", "application/pdf")

Then all we need for a view is:

from django_weasyprint.views import WeasyTemplateResponse

def pdf_view(request, id):
    template = "detail_view.html"
    pdf_filename = "my_report.pdf"

    context = {}
    context["data"] = MyModel.objects.get(id=id)

    return WeasyTemplateResponse(pdf_filename, request=request, template=template, context=context)

Would a PR with this small change and an example for the docs be helpful?

jacklinke avatar Nov 18 '23 02:11 jacklinke

Sounds reasonable... a PR is very welcome! Please include a test.

fdemmer avatar Dec 06 '23 12:12 fdemmer