Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

django: export current queryset to csv by button click in browser

Hello experts! Could you please help. I have few views that return different querysets. my goal is to export current queryset to csv when user click button in browser.

Could you please recommend what is the best algorithm for doing this ? I already did all apart save query to csv only when button is clicked in browser.

Thank you in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...