首页 > 解决方案 > 模板视图中的 Django 文件下载传递值

问题描述

我在 django 中有一个模板视图,在该模板上我有一个下载按钮:

<a href="{% url 'smarts_cfg:template-download' cfg_template.pk %}" class="btn btn-primary">Download file</a>

网址:

path('<int:pk>/edit/download/', smarts_cfg_views.CgfFileDownload.as_view(), name='template-download'),

看法:

class CgfFileDownload(View):
    def get(self, request, pk):
        content = MODEL_NAME.objects.get(pk=pk).name
        response = HttpResponse(content, content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename=%s' % 'testing.txt'
        return response

它按预期工作。我想要做的是在按下按钮并下载文件之前,我希望用户在模板上填写一个字段,并且我想将此信息传递给下载视图(而不将其保存在数据库中)。最好的方法是什么?谢谢!

标签: pythondjango

解决方案


a标签替换为button. 将标签
包裹在按钮上并添加到它。 在 中,您可以添加字段。formtype=submit
forminput

模板

<form method="get" action="{% url 'smarts_cfg:template-download' cfg_template.pk %}">
    <!-- your input field -->
    <input type="text" name="fieldName" />

    <button class="btn btn-primary" type="submit">Download file</button>
</form>

查看

class CgfFileDownload(View):
    def get(self, request, pk):
        # query parameters are stored in `request.GET` dictionary
        fieldValue = request.GET.get('fieldName')

        content = MODEL_NAME.objects.get(pk=pk).name
        response = HttpResponse(content, content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename=%s' % 'testing.txt'
        return response

推荐阅读