我是Django的新手。
我有一个传递变量/对象(configs)的工作模板,并允许我引用对象,例如:
{{ config.id }}
{{ config.hostname }}
一切运行良好,文本在浏览器中显示为纯文本,但我希望能够将此模板中的数据导出为可下载的纯文本文件(不存储在服务器上) ,它将由表单生成,并将用户输入的变量/对象传递给此模板。也许该文件可以像output.txt一样被调用,并且会用熟悉的“打开/另存为”对话框提示用户。
views.py
的例子:
def configs_detail(request, pk):
configs = get_object_or_404(Configurations, pk=pk)
return render(request, 'configs/configs_detail.html', {'configs': configs})
urls.py
url(r'^configs/(?P<pk>[0-9]+)/$', views.configs_detail, name='configs_detail'),
configs_detail.html
模板示例:
{{ configs.hostname }}
{{ configs.state }}
{{ configs.config }}
我已经玩过并下载了纯文本,但似乎无法获得纯文本+变量+下载链接到所有工作。
由于
编辑:感谢Daniel / xbello / danihp的输入
最后得到了它:(这只是一个测试项目,现在它正在工作,它将被清理,并将使用正确的视图名称等)
views.py
:
def special_view(request, pk):
configs = get_object_or_404(Configurations, pk=pk)
return render(request, 'configs/output.txt', {'configs': configs}, content_type='text/plain; charset=utf-8')
def special_view_three(request, pk):
configs = get_object_or_404(Configurations, pk=pk)
response = HttpResponse(content_type='text/plain; charset=utf-8')
response['Content-Disposition'] = 'attachment; filename="output_three.txt"'
t = loader.get_template('configs/output.txt')
c = Context({
'configs': configs,
})
response.write(t.render(c))
return response
urls.py
:
url(r'^special_view/(?P<pk>[0-9]+)/$', views.special_view, name='special_view'),
url(r'^special_view_three/(?P<pk>[0-9]+)/$', views.special_view_three, name='special_view_three'),
configs/output.txt
模板:
{{ configs.hostname }}
{{ configs.state }}
{{ configs.config }}
答案 0 :(得分:4)
render
函数接受名为content_type
的{{3}}。如果将其设置为text/plain
,您应该得到您想要的内容:
render(request, 'configs/output.txt', {'configs': configs},
content_type="text/plain")