Django点击按钮生成Word文档无下载提示仅页面重载问题排查
问题根因
- 你在
TreatmentTemplateView类中自定义的get_doc方法不会被Django自动触发,TemplateView默认收到GET请求后只会执行内置的get方法返回渲染后的HTML页面,所以页面只会重载,不会返回下载响应 - 类视图的方法第一个参数必须是
self,你写的def get_doc(request):参数定义错误,就算手动调用也会报错
修复方案(无需修改路由)
直接重写类视图的get方法,判断请求参数里有没有get_doc,有就走生成Word的逻辑,没有就走原来的渲染页面逻辑:
1. 修改views.py代码
class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context def get(self, request, *args, **kwargs): # 检测是否是生成文档的请求 if 'get_doc' in request.GET: document = Document() docx_title="TEST_DOCUMENT.docx" # ---- Cover Letter ---- document.add_paragraph() document.add_paragraph("%s" % date.today().strftime('%B %d, %Y')) document.add_paragraph('Dear Sir or Madam:') document.add_paragraph('We are pleased to help you with your widgets.') document.add_paragraph('Please feel free to contact me') document.add_paragraph('I look forward to assisting you in this project.') document.add_paragraph('Best regards,') document.add_paragraph('Acme Specialist 1]') document.add_page_break() # 准备下载响应 f = BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + docx_title response['Content-Length'] = length return response # 不是生成文档的请求就走默认渲染页面逻辑 return super().get(request, *args, **kwargs)
2. 可选优化模板
把form的action改为空即可,不需要写#,避免URL末尾多锚点:
<form action="" method="get"> <input type="submit" class="btn btn-primary" value="get_doc" name="get_doc"> </form>
内容的提问来源于stack exchange,提问作者RobMcC
相关产品推荐
相关产品推荐

