Generate PDF in Django admin

Asked

Viewed 294 times

1

How do I get a PDF in the Django admin? I already have the views, I can generate in the frontend with HTML all right, but how do I put a button in the admin to generate or redirect to the pdf link? I’m lost in this.

class EmpresaAdmin(admin.ModelAdmin):
        list_display = ('nome', 'telefone', 'cnpj',)
        search_fields = ('nome', 'cnpj',)
        list_filter = ( 'nome', 'cnpj',  'telefone', )

class AssociadoAdmin(admin.ModelAdmin):
    list_display = ('nome', 'endereco', 'telefone', 'cpf', 'data_filiacao', 'data_nascimento' )   
    search_fields = ('nome', 'cpf',)
    list_filter = ( 'nome', 'cpf',  'telefone', )

class AgendamentoAdmin(admin.ModelAdmin):
    list_display = ('nome','inicio', 'fim','assunto', )  
    search_fields = ('nome', 'cpf',)
    list_filter = ( 'nome', 'inicio',  'assunto', )

views

class Render:
    @staticmethod
    def render(path: str, params: dict, filename: str):
        template = get_template(path)
        html = template.render(params)
        response = io.BytesIO()
        pdf = pisa.pisaDocument(
            io.BytesIO(html.encode("UTF-8")), response)
        if not pdf.err:
            response = HttpResponse(
                response.getvalue(), content_type='application/pdf')
            response['Content-Disposition'] = 'attachment;filename=%s.pdf' % filename
            return response
        else:
            return HttpResponse("Error Rendering PDF", status=400)
  • Generating a button in the admin is not difficult. Choose one of the models and create a function that returns the html of the button. In admin.py list the button as if it were a field but include it in the read_only_fields list.

  • What would this function be like, friend? I’m new to Django, I managed to create with a template on the front, but in admin.

1 answer

0

you have here an example of how to do this, you need to use an ACTION, something like this:

from django.http import HttpResponse
from django.template.loader import render_to_string

from .models import Report

from weasyprint import HTML

class EmpresaAdmin(admin.ModelAdmin):
        list_display = ('nome', 'telefone', 'cnpj',)
        search_fields = ('nome', 'cnpj',)
        list_filter = ( 'nome', 'cnpj',  'telefone', )

class AssociadoAdmin(admin.ModelAdmin):
    list_display = ('nome', 'endereco', 'telefone', 'cpf', 'data_filiacao', 'data_nascimento' )   
    search_fields = ('nome', 'cpf',)
    list_filter = ( 'nome', 'cpf',  'telefone', )

class AgendamentoAdmin(DjangoObjectActions, admin.ModelAdmin):
    list_display = ('nome','inicio', 'fim','assunto', )  
    search_fields = ('nome', 'cpf',)
    list_filter = ( 'nome', 'inicio',  'assunto', )

    def generate_pdf(self, request, obj):
        html_string = render_to_string('reports/pdf_template.html', {'obj': obj})

        html = HTML(string=html_string)
        html.write_pdf(target='/tmp/{}.pdf'.format(obj));

        fs = FileSystemStorage('/tmp')
        with fs.open('{}.pdf'.format(obj)) as pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="{}.pdf"'.format(obj)
            return response

        return response

    generate_pdf.label = 'Gerar PDF'
    generate_pdf.short_description = 'Clique para gerar o PDF dessa ordem de serviço'

    change_actions = ('generate_pdf',)

NOTE: The option will be available in the actions dropdownlist, where you can delete the Selectable Switches. The key to get available is the last line of code I share...." change_actions = ('generate_pdf',)".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.