django csv下载查询集

时间:2014-06-20 09:54:15

标签: django csv

这是我的观点..

class SingleNewsView(ListView):
    model = News
    form_class = SearchForm
    template_name = "single_news.html"



    def get(self, request, pk, **kwargs):
        self.pk = pk

        self.pub_from = request.GET.get('pub_date_from')
        self.pub_to = request.GET.get('pub_date_to')
        self.crawlers = request.GET.get('crawler')

        print self.crawlers


        return super(SingleNewsView,self).get(request,pk, **kwargs)

    def get_context_data(self, **kwargs):

        context = super(SingleNewsView,self).get_context_data(**kwargs)
        context["form"] = SearchForm#(self.request.GET)
        context["something"] = News.objects.filter(category_id=self.pk).filter(published_date__range=(self.pub_from,self.pub_to), crawler=self.crawlers)

        return context

此处在显示此视图的同一页面上,我想要"下载CSV"选项,并希望下载由上下文返回的查询的csv ["某些"]。我怎样才能做到这一点 ??任何帮助..

我也写了下载csv的视图,但很困惑..

def CSVView(request):
    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = 'attachment; filename=somefilename.csv"'

    writer = csv.writer(response)
    writer.writerow([News.objects.filter(what goes here ???])

    return response

2 个答案:

答案 0 :(得分:0)

这是我创建csv文件的方法,填写它并将其发送到模板下载:

def my view():
...    ...    ...
output_file = open('path/new_file_name', 'wb')
writer = csv.writer(output_file, delimiter=';')  # Delimiter is not needed
# This is to show a "title" per column:
headers = ['column1', 'column2', 'column3', 'column4']  
writer.writerow(headers)
for item in item_list:  # Then add the info you need to the file from the objects
    writer.writerow('write what you need for each item')

response = StreamingHttpResponse(writer, content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename="FILENAME.csv"'
return response

当您使用StreamingHttpResponse并按照我向您展示的方式创建响应时,当您执行返回响应时,它会自动开始下载您发回的文件

答案 1 :(得分:0)

最近我发现django-queryset-csv库非常有用。有了这个,你的代码归结为:

from djqscsv import render_to_csv_response


class SingleNewsView(ListView):
    model = News
    form_class = SearchForm
    template_name = "single_news.html"

    def get(self, request, pk, **kwargs):
        self.pk = pk

        self.pub_from = request.GET.get('pub_date_from')
        self.pub_to = request.GET.get('pub_date_to')
        self.crawlers = request.GET.get('crawler')

        self.format = request.GET.get('format', False)

        # check for format query key in url (my/url/?format=csv)
        if self.format == 'csv':
            qs = News.objects.filter(category_id=self.pk)\
                             .filter(published_date__range=(self.pub_from,self.pub_to), crawler=self.crawlers)\
                             .values('id', 'name')
            return render_to_csv_response(qs)

        print self.crawlers

        return super(SingleNewsView,self).get(request,pk, **kwargs)

    def get_context_data(self, **kwargs):

        context = super(SingleNewsView,self).get_context_data(**kwargs)
        context["form"] = SearchForm#(self.request.GET)
        context["something"] = News.objects.filter(category_id=self.pk).filter(published_date__range=(self.pub_from,self.pub_to), crawler=self.crawlers)

        return context

当然,您需要使用自己想要输出的列名,而不是id,name ..

既然我没有看到你如何呈现下载csv按钮,我无法告诉你如何添加格式键到它的网址。