将django管理员中的应用程序中的特定数据导出为pdf

时间:2019-05-27 01:50:38

标签: django python-3.x django-admin

我已经设置了将数据导出为pdf格式所需的所有内容。现在,我的问题是如何对django管理员执行此用例。我可以在提供类视图的同时通过操作完成此操作,然后在操作中将该特定的类视图添加到模型管理员中吗?那可能吗?我该怎么办?

这是我的课程视图

class PdfCarrier(View):

    def get(self, request, carrier_id):
        carrier = Carrier.objects.filter(id=carrier_id).first()
        params = {
        'today': timezone.now(),
        'carrier': carrier,
        'request': request
        }

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = "inline; filename=Carrier-Report.pdf"

        html = render_to_string('carrier/carrier_pdf.html', params)
        css = [
            base.BASE_DIR + '/src/css/bootstrap3/css/bootstrap.min.css'
        ]

        HTML(string=html).write_pdf(response, stylesheets=css)
        return response
        # return Render.render('carrier/carrier_print.html', params)

我提供的网址。

    path('<uuid:carrier_id>/carrier-report.pdf', views.PdfCarrier.as_view(), name="print_carrier"),

1 个答案:

答案 0 :(得分:0)

那是可能的。在模型管理类中,将pdf路径添加到内置URL列表的前面。

class YourModelAdmin(admin.ModelAdmin):
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('<uuid:carrier_id>/carrier-report.pdf', self.pdf_view),
        ]
        return custom_urls + urls

然后定义方法pdf_view,如下所示。

class YourModelAdmin(admin.ModelAdmin):
    ...
    def pdf_view(self, request, carrier_id):
        # do whatever you want
        # and return the response

就是这样。