问题描述:

I am very new to Django.

I have a working template that passes a variable/object (configs) and allows me reference objects such as:

{{ config.id }}

{{ config.hostname }}

All is working well and the text shows up as plain text in the browser, but I would like to be able to export the data from this template to a plain text file that can be downloaded (that is not stored on the server, it would be generated by a form) and have the variables/objects that users enter passed to this template. Perhaps the file could be called something like output.txt and would prompt the user with the familiar 'open with/save as' dialog box.

example of views.py:

def configs_detail(request, pk):

configs = get_object_or_404(Configurations, pk=pk)

return render(request, 'configs/configs_detail.html', {'configs': configs})

example of urls.py

url(r'^configs/(?P<pk>[0-9]+)/$', views.configs_detail, name='configs_detail'),

example of configs_detail.html template:

{{ configs.hostname }}

{{ configs.state }}

{{ configs.config }}

I have played around and gotten the download of plain text to work but cannot seem to get the plain text + variables + download link to all work together.

Thanks

edit: thanks to Daniel / xbello / danihp for their inputs

Answer:

Finally got it to work with: (this is just a test project, now it's working it will be cleaned up and proper view names etc will be used)

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 template:

{{ configs.hostname }}

{{ configs.state }}

{{ configs.config }}

网友答案:

The render function accepts an optional parameter called content_type. If you set it as text/plain you should get what you want:

render(request, 'configs/output.txt', {'configs': configs},
       content_type="text/plain")
相关阅读:
Top