将额外上下文传递给django中的列表视图

发布于 2025-02-02 12:05:24 字数 511 浏览 1 评论 0原文

谁能告诉我如何将我的listView上的“查询”作为上下文传递,同时将“ search_results”作为Context_Object_name?我只是无法绕过它:

class SearchResulView(ListView):
    model = Product
    template_name = 'shop/product/search_results.html'
    context_object_name = 'search_results' 

    def get_queryset(self):
        query = self.request.GET.get("q")
        search_results = Product.objects.filter(
            Q(name__icontains=query)
            )
        return search_results

正在尝试将传递给“查询”的值渲染到我的模板上,但我无法弄清楚如何...

Can anyone please tell me how I can pass the "query" on my ListView as a context while at the same time keeping "search_results" as a context_object_name? I just can't get my head around it:

class SearchResulView(ListView):
    model = Product
    template_name = 'shop/product/search_results.html'
    context_object_name = 'search_results' 

    def get_queryset(self):
        query = self.request.GET.get("q")
        search_results = Product.objects.filter(
            Q(name__icontains=query)
            )
        return search_results

Am trying to render the values passed to "query" on my template but I just can't figure out how...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痴者 2025-02-09 12:05:24

您可以通过覆盖 .get_context_data(…) method> nbsp; [django-doc> [django-doc]

class SearchResulView(ListView):
    model = Product
    template_name = 'shop/product/search_results.html'
    context_object_name = 'search_results' 

    def get_queryset(self):
        return super().get_queryset().filter(
            name__icontains=self.request.GET.get('q')
        )

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['query'] = self.request.GET.get('q')
        return context

您无需覆盖.get_context_data(…)方法。在模板中,您可以使用以下方式访问此操作:

{{ view.request.GET.q }}

You can pass this by overriding the .get_context_data(…) method [Django-doc]:

class SearchResulView(ListView):
    model = Product
    template_name = 'shop/product/search_results.html'
    context_object_name = 'search_results' 

    def get_queryset(self):
        return super().get_queryset().filter(
            name__icontains=self.request.GET.get('q')
        )

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['query'] = self.request.GET.get('q')
        return context

You however do not need to override the .get_context_data(…) method. In the template you can access this with:

{{ view.request.GET.q }}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文