Django:添加对generic.DetailView的附件

时间:2018-02-08 11:32:53

标签: django django-views

我有一个现有的Django应用程序,其中包含UserProfiles的详细信息视图。现在,我们的客户希望能够将页面信息“下载”为PDF。

我在HTML中添加了一个按钮来触发'generate-attachement'方法

<div class="input-group">
        <button name='zip' value="True" type="submit">Get report</button>
</div>

我还在视图中添加了'generate_pdf'方法,该方法由上面的按钮触发。

class ProfileView(ProfileMixin, generic.DetailView):
    template_name = 'user/profile/detail.html'

    def get_object(self, queryset=None):
        return self.context.profile_user    

    def generate_pdf(self):
        from reportlab.pdfgen import canvas    
        response = HttpResponse(content_type='application/pdf')
        response['pdf'] = 'attachment; filename="summary.pdf"'
        p = canvas.Canvas(response)
        p.drawString(100, 100, "Hello world.")
        p.showPage()
        p.save()
        print(p)
        return response    

    def get_context_data(self, **kwargs):
        data = super(ProfileView, self).get_context_data(**kwargs)

        #Check if 'get attachement' button has been pressed
        if self.request.GET.get('zip', None):
            self.generate_pdf()


        #Code to load relevant data form a large number of models
        #append it to the 'data' variable . 
        #(e.g data['group_year] = ...etc

        return data

然而,当我运行此代码/按下按钮时,方法/打印命令全部被触发,但没有附件返回到浏览器

<reportlab.pdfgen.canvas.Canvas instance at 0x112165638>
[08/Feb/2018 12:30:08] "GET /user/profile/459/?zip=True HTTP/1.1" 200 41749

然而我从the official Django Documentation获得了大部分代码,所以我不清楚为什么我的代码失败了。

有没有人知道我做错了什么?

2 个答案:

答案 0 :(得分:2)

您需要覆盖视图的get()方法以自定义响应:

class ProfileView(ProfileMixin, generic.DetailView):
    template_name = 'user/profile/detail.html'

    def get(self, request, *args, **kwargs):
        #Check if 'get attachement' button has been pressed
        if self.request.GET.get('zip', None):
            return self.generate_pdf()
        return super(ProfileView, self).get(request, *args, **kwargs)

答案 1 :(得分:1)

看起来你应该使用'Content-Disposition'而不是'pdf'来将你的文件添加到响应中。

response['Content-Disposition'] = 'attachment; filename="summary.pdf"'