Django REST Framework - PDF Generator 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&lt;pk&gt;[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/
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']