2015-12-24 44 views
2

我嘗試在Django中使用基於類的視圖。我有這樣的問題:我爲博客定義了一個基類(BlogBaseView)和另外兩個繼承它的類。 而在第二類(BlogIndexView)我想通過獲取請求進行搜索,所以我已經覆蓋了get方法。它的工作原理,但如果我沒有得到請求,它會返回HttpResponse,但我想返回通常的上下文(其中BlogIndexView retread不覆蓋get方法)。如何返回重寫get方法中的常規響應,Django

我該怎麼辦?

class BlogBaseView(View): 

    def get_context_data(self, **kwargs): 
     context = super(BlogBaseView, self).get_context_data(**kwargs) 
     blog_categories = [] 
     categories = BlogCategory.objects.all() 
     for category in categories: 
      blog_categories.append(tuple([category, category.get_number_of_category_items])) 

     context['name_page'] = 'blog' 
     context['tags'] = Tag.objects.all() 
     context['blog_categories'] = blog_categories 
     return context 

class BlogIndexView(BlogBaseView, ListView): 
    queryset = Post.objects.all().order_by('-date_create') 
    template_name = 'index_blog.html' 
    context_object_name = 'posts' 

    def get(self, request): 
     if request.GET.get('tag'): 
      context = { 
       'posts' : Post.objects.filter(tags__name__in=[request.GET.get('tag')]) 
      } 
      return render(request, self.template_name, context) 
     return HttpResponse('result') 

class BlogFullPostView(BlogBaseView, DetailView): 
    model = Post 
    template_name = 'full_post.html' 
    pk_url_kwarg = 'post_id' 
    context_object_name = 'post' 

謝謝!

+0

不知道你在做什麼。你的意思是BlogIndexView應該使用與BlogBaseView相同的上下文並將Post對象添加到上下文中? – danielcorreia

+0

不,BlogIndexView - 顯示列表中的所有帖子,BlogFullPostView - 顯示一個完整帖子,並且BlogBaseView爲兩個繼承類(BlogFullPostView和BlogIndexView)傳遞相同的上下文(例如側欄) –

+0

好的。同樣的答案仍然適用,如果您確實需要重寫get方法,請確保調用self.get_context_data,否則請在下面嘗試我的答案。 – danielcorreia

回答

2

ListView類也有一個get_context_data方法,所以你應該重寫,而不是get方法。使用super您可以訪問BlogBaseView.get_context_data,然後您可以擴展結果。

方法如下:

class BlogIndexView(BlogBaseView, ListView): 
    queryset = Post.objects.all().order_by('-date_create') 
    template_name = 'index_blog.html' 
    context_object_name = 'posts' 

    def get_context_data(self, **kwargs): 
     # use the (super) force Luke 
     context = super(BlogIndexView, self).get_context_data(**kwargs) 
     if self.request.GET.get('tag'): 
      context['posts'] = Post.objects.filter(tags__name__in=[self.request.GET.get('tag')]) 
     return context 
+0

但它會導致錯誤:'名稱'請求'未定義' –

+0

我可以問你一些事嗎?方法'get_context_data'和'get'方法有什麼區別? –

+0

當然!簡而言之,當向視圖發出GET請求並返回一個HttpResponse時,會調用get方法。 get方法有什麼作用?它取決於它是一個ListView,DetailView,FormView,...但他們都調用'get_context_data'來插入上下文到模板中。你清楚了嗎? – danielcorreia

1

如果您正在覆蓋ListView那就不是重寫get方法,因爲你會失去很多的ListView功能是一個好主意。

在這種情況下,重寫get_queryset並在那裏進行搜索會更好。

def get_queryset(self): 
    queryset = super(BlogIndexView, self). get_queryset() 
    if request.GET.get('tag'): 
     queryset = queryset.filter(tags__name=request.GET['tag']) 
    return queryset 
相關問題