从管理员模型将Django模型导出为pdf

meh*_*een 0 python pdf django

我想使用reportlab直接从模型管理员将模型导出为pdf文件。

class InvoiceItem(models.Model):
    invoice_number = models.CharField(max_length=50)
    invoice_date = models.DateField('Invoice date')
    invoice_sent = models.BooleanField()
    invoice_paid = models.BooleanField()
Run Code Online (Sandbox Code Playgroud)

而我的模型管理员:

class InvoiceItemAdmin(admin.ModelAdmin):
    def pdf_version(self, obj):
    ## how to call my reportlab view here ??
Run Code Online (Sandbox Code Playgroud)

请帮助,M。

yuv*_*uvi 5

使用动作!我认为您已经创建了reportlab视图,并且只想使用模型项将其重定向到该视图。所以创建一个这样的函数(在任何类之外):

def pdf_version(modeladmin, request, queryset):
    url = '/your_pdf_url/?pks=' + ','.join([q.pk for q in queryset])
    HttpResponseRedirect(url)
Run Code Online (Sandbox Code Playgroud)

然后在管理员中:

class InvoiceItemAdmin(admin.ModelAdmin):
    actions = [pdf_version]
Run Code Online (Sandbox Code Playgroud)

在该示例中,我使用GET数据一次允许一个以上的报告,因为这似乎是合理的,但是您可以根据需要随意更改它。就这么简单。另请查看文档以获取更多详细信息