3
\$\begingroup\$

I created a new endpoint for an API (Django REST Framework) that generates a PDF from an HTML template. I follow the example from the plugin django-easy-pdf.

It's working, but I would like to improve and to know what could be done in a better way.

Asset is an object from the database with information. The idea is to print some rows on an HTML template to then convert to PDF. The HTML is fine, but I'm just not sure if I could improve on this view.

URLs:

 url(r'^report/asset/(?P<pk>[0-9]+)$', api.DemoPDFView.as_view()),

views.py

from easy_pdf.views import PDFTemplateResponseMixin, PDFTemplateView


class DemoPDFView(PDFTemplateView):
    template_name = 'reports/asset.html'
    pdf_filename = 'asset.pdf'

    def get_context_data(self, **kwargs):
        pk = self.kwargs.get('pk', None)

        asset = Asset.objects.get(id=pk)
        project = asset.project.name
        id = asset.id
        name = asset.title

        return super(DemoPDFView, self).get_context_data(
            pagesize='A4',
            title='Asset',
            project=project,
            name=name,
            id=id,
            **kwargs
        )

The plugin is available:

http://django-easy-pdf.readthedocs.io/en/v0.2.0-dev1/ 
\$\endgroup\$
  • \$\begingroup\$ This looks like a corrected version of this other question, posted by a different user yesterday. I suspect both user accounts belong to you, correct me if I'm wrong. It would have been better to edit the first question, we would have reopened it. \$\endgroup\$ – janos May 30 '17 at 11:28
  • \$\begingroup\$ right. There was some bug, i coudn't log in the that account for some reason, even to reset password was impossible \$\endgroup\$ – crazy_sec May 30 '17 at 11:35
1
\$\begingroup\$

You have a URL endpoint with a numeric parameter to retrieve an asset and generate a PDF report. But the parameter is not validated. Django will ensure that the value is numeric, thanks to the way you defined the endpoint, but the asset might not exist. When a nonexistent asset is requested, the program will crash.

Since kwargs is a parameter of get_context_data, it would be better to access it directly, rather than through self.kwargs.

Since Django ensures that the pk parameter exists, you can write simpler like this:

pk = kwargs['pk']
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.