Aaeronn
Aaeronn

Reputation: 155

django download query as csv

Here is my view

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',False)
    self.pub_to = request.GET.get('pub_date_to',False)
    self.crawlers = request.GET.get('crawler',False)

    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)
    if self.pub_from and self.pub_to and self.crawlers:
        context["something"] = News.objects.filter(category_id=self.pk).filter(published_date__range=(self.pub_from,self.pub_to), crawler=self.crawlers)
    else:
        context["something"] = News.objects.filter(category_id=self.pk)

    return context

I want to download the news as csv. When I click "Download CSV" on the news listing page I want to download the query that came after filter. How can I do that?? Any help??

Upvotes: 0

Views: 557

Answers (3)

lunamystry
lunamystry

Reputation: 321

I found the following code snippet from the django docs helpful:

import csv
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

    return response

Upvotes: 0

lethe3000
lethe3000

Reputation: 1

I use xlwt to export models to excel, I think this code can FYI

from xlwt import Workbook
def get(self, request, *args, **kwargs):
    book = Workbook(encoding='utf-8')
    // fill book with your data here...
    response = HttpResponse(content_type='application/ms-excel')
    book.save(response)
    response['Content-Disposition'] = 'attachment; filename="%s"' % self.excel_file_name.encode("utf-8")
    response['Cache-Control'] = 'no-cache'
    return response

Upvotes: 0

Greg
Greg

Reputation: 1991

Django has its own csv library. If that doesn't suit what you're looking for maybe check out django-data-export. Good luck and hope this helps!

Upvotes: 1

Related Questions