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/ 
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 30, 2017 at 9:40
\$\endgroup\$
2
  • \$\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\$ Commented May 30, 2017 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\$ Commented May 30, 2017 at 11:35

1 Answer 1

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']
answered May 30, 2017 at 16:37
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.