【问题标题】:Get GET url parameters in class-base views for Django 3.2在 Django 3.2 的基于类的视图中获取 GET url 参数
【发布时间】:2021-04-30 03:54:42
【问题描述】:

我发现了一个类似的问题,但它是针对 Django 1.5 的,我认为它不适合我。

class SearchedPostListView(ListView):
    model = Post
    template_name = 'blog/search.html'  # <app>/<model>_<viewtype>.html
    paginate_by = 2
    context_object_name = 'posts'   

    def get_context_data(self, *args, **kwargs):
        context = super(SearchedPostListView, self).get_context_data(*args, **kwargs)
        query = self.kwargs.get('q')
        context['posts'] = Post.objects.filter(Q(title__icontains=query) | Q(author__username__icontains=query) | Q(content__icontains=query))
        context['categories'] = Categories.objects.all
        return context

这是我的代码。我正在尝试搜索我网站上的所有帖子,并且我正在显示标题中包含查询的所有帖子。

所以,如果我输入 URL localhost:8000/search?q=foo,那么它必须向我显示标题中包含单词 foo 的帖子。

但我无法访问 GET 参数。如何在 Django 3.2 中访问 GET 参数?

【问题讨论】:

  • 与基于函数的视图相同,self.request.GET.get("q")

标签: python django get


【解决方案1】:

使用query = self.request.GET.get('q') 代替query = self.kwargs.get('q')

    class SearchedPostListView(ListView):
        model = Post
        template_name = 'blog/search.html'  # /_.html
        paginate_by = 2
        context_object_name = 'posts'   
    
        def get_context_data(self, *args, **kwargs):
            context = super(SearchedPostListView, self).get_context_data(*args, **kwargs)
            query = self.request.GET.get('q')
            context['posts'] = Post.objects.filter(Q(title__icontains=query) | Q(author__username__icontains=query) | Q(content__icontains=query))
            context['categories'] = Categories.objects.all
            return context

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 2013-03-23
    • 2018-12-09
    • 2015-04-30
    • 2012-12-28
    • 2012-01-25
    • 2019-03-14
    • 2017-04-17
    相关资源
    最近更新 更多