fdemmer / django-weasyprint

A Django class-based view generating PDF resposes using WeasyPrint
Other
352 stars 53 forks source link

Recommend defaulting content_type to PDF #75

Open jacklinke opened 11 months ago

jacklinke commented 11 months ago

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?

fdemmer commented 11 months ago

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