python - 模板视图中的 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
它按预期工作。我想要做的是在按下按钮并下载文件之前,我希望用户在模板上填写一个字段,并且我想将此信息传递给下载视图(而不将其保存在数据库中)。最好的方法是什么?谢谢!
解决方案
将a
标签替换为button
. 将标签
包裹在按钮上并添加到它。
在 中,您可以添加字段。form
type=submit
form
input
模板:
<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
推荐阅读
- reactjs - 在 React(样式化组件)中定位一个 svg 来编辑它
- sails.js - Sails.js 默认应用无法使用 MongoDb 启动
- css - React Native z-index 奇怪的行为
- python - 单击 HTML 按钮在后端运行 Python 程序
- python - 使用 for 循环创建不同的列表变量名称
- vba - Me!control_textbox.Requery 运行时错误 '438' 对象不支持此属性或方法
- html - HTML - 由 tbody 元素建立的行组的第 2 行没有以它开头的单元格
- python - 如何修复值错误:“CB7”不在列表中?
- arrays - 如何检查直线多边形是否相交
- typo3 - 有时不会生成排版链接