If you are using classed based views, its really easy (this is the sort of task where they shine). Subclass the main view, override the template and content type.
Here is an example from one of my projects
views.py
class SavedSamplesView(ListView):
"""
This is the standard view returning HTML
"""
template_name = "SavedSamples.html"
model = Sample
context_object_name = "sample_list"
def get_queryset(self) :
slug = self.kwargs['submission_slug']
return Sample.objects.filter(submission__submission_slug=slug)
class SavedSamplesCsvView(SavedSamplesView):
"""
Subclass of above view, to produce a csv file
"""
template_name = 'SavedSamples.csv'
content_type = 'text/csv'
The template SavedSamples.cvs looks like this (the formatting to get the newline is a little ugly, but it works). The first line is the headers, remove that if you don't need it:
sample.id , sample.name , ... , comments
{% for sample in sample_list %}{{ sample.id }},{{ sample.name }},....,{{sample.comments}}
{% endfor %}
urls.py
url(r'^savedsamplescsv/(?P<submission_slug>[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-_]+)/', views.SavedSamplesCsvView.as_view(), name='saved_samples_csv'),
I would use a link instead of a button, and style it as button.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…