在下面的代码中,我通过自定义在管理页面中添加了一个“另存为pdf”按钮。当我点击另存为pdf按钮时,它应以pdf格式显示当前页面的详细信息。我无法检索当前页面的单独数据,无法以pdf格式显示(my_template.html
)。怎么做?提前谢谢。
views.py
:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Create your views here.
from django.http import HttpResponse
from django.views.generic import View
from django.db import models
from details.utils import render_to_pdf #created in step 4
from .models import UserDetails
class GeneratePdf(View):
def get(self, request, *args, **kwargs):
#THIS IS THE PLACE WHERE I GET STUCK
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')
urls.py
:
"""myapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from details.views import GeneratePdf
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^pdf/$', GeneratePdf.as_view(),name='generatepdf'),
]
答案 0 :(得分:1)
Anton Shurashov's answer是正确的。除此之外,在模板中指定所需标记中的URL时,您应该知道要访问它的数据的ID。它仅在数据保存在数据库中时才有效。
{%url 'generatepdf' adminform.form.instance.id %}
"""adminform.form.instance.id"""
是指示当前页面数据ID的一般实例。
只有在保存数据后,该按钮才可见。
答案 1 :(得分:0)
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')