2013-05-09 60 views
1

我有一个视图,放置一些上下文,并从这个上下文呈现模板。如果没有搜索查询,我希望查看显示的所有内容,并显示搜索到的内容,如果搜索到任何内容。django haystack - 如何使用当前视图有一些上下文

class MyCurrentView(View): 
    def get(self, request): 
     data = { 'users': User.objects.all() } 
     return render_to_response("mytemp.html", .. 

urls.py: 
     url(r'^search/$', MyCurrentView.as_view()) 

现在,我与搜索查看这样的集成这样的:如果有必要

class MyCurrentView(SearchView): (If u observe, I subclassed SEarchView). 
    template = 'mytemp.html' 
    def get(self, request): 
     data = { 'users': User.objects.all() } 
     return render_to_response... 

    def get_context_data(self, ...): 
      print "....this should print" #But not printing. So, unable to add data 
    return data 

urls.py: 
     url(r'^search/$', MyCurrentView.as_view()) 
     # as_view() gave me error, so I did MyCurrentView() , may be thats y, get_context_data not calling. 

将提供更多的信息。

+0

得到了这个答案,只是重写extra_context定义。但是,谁能告诉我在urls.py中调用VIEwname.as_view()和ViewName()之间的区别? – user2139745 2013-05-09 16:08:08

+0

Haystack的SearchViews不像Django的常规基于类的视图。他们不使用'as_view'模式。 – 2013-05-10 13:37:52

+0

Haystack现在通过PR#1130拥有传统的django CBV。看到我的评论下面或https://github.com/toastdriven/django-haystack/pull/1130 – 2015-01-14 15:18:00

回答

0

新的Django样式类通过PR#1130加为本次到Django的干草堆:

您现在可以使用搜索视图就像你通常会使用Django(见变化在拉请求中)。

from haystack.generic_views import SearchView 

class MySearchView(SearchView): 

    def get_context_data(self, **kwargs): 
     # do whatever you want to context 
相关问题