ares314
ares314

Reputation: 1

How do you implement content-disposition as an attachment for django_weasyprint package?

Using the django_weasyprint (class-based view implementation) package to generate a pdf.

I'm able to generate a pdf in the browser but have trouble setting up a open/save-as dialog box pop-up feature. I know I have to set content-disposition equal to attachment (I think) but I'm struggling doing so.

from django.conf import settings
from django.views.generic import DetailView

from django_weasyprint import WeasyTemplateResponseMixin


class ArticleView(DetailView):
    # vanilla Django DetailView
    model = Article
    template_name = 'article_detail.html'


class ArticlePrintView(WeasyTemplateResponseMixin, ArticleView):
    # output of DetailView rendered as PDF
    pdf_stylesheets = [
        settings.STATIC_ROOT + 'css/app.css',
    ]

I'd like to have the open/save-as dialog box to pop-up automatically.

Upvotes: 0

Views: 424

Answers (1)

solarissmoke
solarissmoke

Reputation: 31424

Have a look at the code for the WeasyTemplateResponseMixin - there is the option to set pdf_filename on the class, and if you do that, then the Content-Disposition header will be set with this file name, so that the browser opens a download/save dialog for the file. Something like this:

class ArticlePrintView(WeasyTemplateResponseMixin, ArticleView):

pdf_filename = 'my-pdf.pdf'

If you need to determine the file name dynamically then you can override the get_pdf_filename method to do that:

def get_pdf_filename(self):
    return 'some-file.pdf'

Upvotes: 1

Related Questions