2015-09-07 40 views
2

我在我的应用程序中使用基于类的视图,但我卡在一点。我正在使用ListView并创建了两个类,分别是ListView的子类。Listview基于类的视图无法正常工作

views.py

class blog_home(ListView): 
    paginate_by = 3 
    model= Blog 
    context_object_name = 'blog_title' 
    template_name = 'blog.html' 

class blog_search(ListView): 
    paginate_by = 4 

    context_object_name = 'blog_search' 
    template = 'blog_search.html' 

    def get_queryset(self): 
     self.search_result = Blog.objects.filter(title__contains = 'Static') 
     return self.search_result 

urls.py

urlpatterns = [ 
url(r'^$', index, name='index'), 
url(r'^grappelli/', include('grappelli.urls')), 
url(r'^blog/', blog_home.as_view(), name='blog_home'), 
url(r'^admin/', include(admin.site.urls)), 
url(r'^blog/search/',blog_search.as_view(),name='blog_search'), 
] 

在我blog_Search()上面的代码中,get_queryset()方法是没有得到调用。我的意思是它没有工作。如果我在blog_home中使用相同的方法,它确实有效。

blog_search不过滤。我也添加了打印语句,但没有被调用。

我可以用ListView在同一个文件中创建两个类吗?这是问题吗?

+1

请显示urls.py文件。 –

+0

您是否收到任何运行错误? – electrometro

+0

你不需要在第二个中定义'model = Blog'吗? – dietbacon

回答

3

您需要终止您的blog/ URL项。如果没有终止,它会匹配以“blog /”开头的所有网址,包括“博客/搜索”,因此没有任何请求会将其添加到blog_search视图。

url(r'^blog/$', blog_home.as_view(), name='blog_home'), 
url(r'^admin/', include(admin.site.urls)), 
url(r'^blog/search/$',blog_search.as_view(),name='blog_search'),