这是我的观点
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
我想将新闻下载为csv。当我点击新闻列表页面上的“下载CSV”时,我想下载过滤后的查询。我怎样才能做到这一点??任何帮助?
答案 0 :(得分:1)
Django有自己的csv library。如果这不适合您正在寻找的东西,可以查看django-data-export。祝你好运,希望这有帮助!
答案 1 :(得分:0)
我使用xlwt将模型导出为excel,我认为此代码可以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
答案 2 :(得分:0)
我在django docs帮助中找到了以下代码段:
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