django继承上下文变量

时间:2014-06-25 06:17:45

标签: django inheritance

这是我的观点,根据过滤器,我有新闻列表...

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

现在我在这里查看下载从上下文查询的新闻列表["某事"]。

def CSVView(request):

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

writer = csv.writer(response)


writer.writerow([context["something"])# Here what can I write...

return response

现在在writer.writerow中的def CSVView中,我希望上下文["某些"]形成第一个视图。我不知道该怎么做。我想在csv中下载新闻。谁有更好的主意?我做错了什么?

我已经尝试了def CSVView(请求,SingleNewsView):但是它说defCS只需要2个争论1给出错误。我应该做些什么。如何以csv格式下载新闻?

1 个答案:

答案 0 :(得分:0)

正如我评论的那样,你应该省略上下文的使用,在这种情况下你需要的是会话,在你的代码看起来如下:

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)

        if self.pub_from and self.pub_to and self.crawlers:
            value = News.objects.filter(category_id=self.pk).filter(published_date__range=(self.pub_from,self.pub_to), crawler=self.crawlers)  
        else:
            value= News.objects.filter(category_id=self.pk)
        self.request.session.set("somekey",value)
        return super(SingleNewsView,self).get(request,pk, **kwargs)


def CSVView(request):

    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = 'attachment; filename=somefilename.csv"'
    writer = csv.writer(response)
    writer.writerow(self.request.session.get("somekey"))

    return response