[Answered ]-Django admin page adding save as pdf button

1👍

Anton Shurashov’s answer is correct. In addition to that, in the template while specifying the URL in the required tag, you should know the ID of the data to access it. It will work only when the data is saved in the database.

{%url 'generatepdf' adminform.form.instance.id  %}

"""adminform.form.instance.id""" is the general instance indicating the ID of the current page data.

The button should be visible only after saving the data.

1👍

urls.py:

from details.views import GeneratePdf

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^pdf/(?P<user_id>[0-9]+)/$', GeneratePdf.as_view(), name='generatepdf'),
]

views.py:

from django.http import HttpResponse
from django.views.generic import View
from django.db import models
from details.utils import render_to_pdf
from .models import UserDetails

class GeneratePdf(View): 
    def get(self, request, *args, **kwargs):
        obj = UserDetails.objects.get(id=kwargs.get('user_id'))
        all = {
            "Name": obj.name,
            "Email": obj.email,
            "Address": obj.address,
            "DOB": obj.dob,
            "Gender": obj.gender,
        } 
        pdf = render_to_pdf('my_template.html', all)
        return HttpResponse(pdf, content_type='application/pdf')

Leave a comment