18910140161

Python-获取在Django中执行函数的按钮-堆栈溢出

顺晟科技

2022-10-18 13:06:27

140

我想网页的用户点击一个按钮来产生一个Word文档。

然而,

目前,当用户单击该按钮时,页面只是重新加载并将“?获取_文档=获取_文档#”附加到URL.

相反,我希望提示用户下载生成的文档。

url.py

app_name = "patient"
urlpatterns = [
    path('add/', views.PatientAddView.as_view(), name="patient_add"),
    path(
        route='<patient_id>/',
        view=views.TreatmentTemplateView.as_view(),
        name='treatment_detail'),

]

视图.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_doc(request):
        print('running9')
        # if(request.GET.get('get_doc')):
        if 'get_doc' in request.GET:
            print('running')
            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()

            # Prepare document for download        
            # -----------------------------
            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

HTML

{% extends "base.html" %}

<!-- {% block title %}Patient: {{ patient.name }}{% endblock %} -->
{% block content %}

<h3>Patient Summary</h3>
<p>
    {{pt_letter|linebreaks}}
</p>


<form action="#" method="get">
<input type="submit" class="btn btn-primary" value="get_doc" name="get_doc">
</form>

{% endblock content %}

顺晟科技:

您需要的是指定发送GET请求的路由。简单地在下面应该工作

<代码><;表单操作=";{%URL '患者_添加'%}";方法=";获取";>;<;输入类型=";提交";类=";btn btn-primary";value=";获取_文档";名称=";获取_文档";>;<;/窗体>;
  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航