Skip to main content
 首页 » 编程设计

python之如何在覆盖 get 方法 Django 中返回常规响应

2024年08月23日33zfyouxi

我尝试在 Django 中使用基于类的 View 。我有这样的问题:我为博客定义了一个基类 (BlogBaseView) 和另外两个继承它的类。 在第二个类 (BlogIndexView) 中,我想通过 get 请求进行搜索,所以我重写了 get 方法。它有效,但如果我不发出 get 请求,它会返回 HttpResponse,但是我想返回通常的上下文(BlogIndexView 重新调整而不覆盖 get 方法)。

我能做什么?

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' 

谢谢!

请您参考如下方法:

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