【问题标题】:search bar add as a base template into one class views Django搜索栏作为基本模板添加到一个类视图中 Django
【发布时间】:2023-03-22 04:10:01
【问题描述】:

views.py

class BookList(ListView):
    model = Book
    context_object_name = 'book_list'
    template_name = 'books/book_lists.html'
    paginate_by = 12
    extra_context = {
        'category_list': Category.objects.all(),
        'author_list': Author.objects.all(),
        'language_list': Language.objects.all(),
    }

    def get_queryset(self):
        query = self.request.GET.get('q')
        if query:
            object_list = self.model.objects.filter(
                Q(name_of_the_book__icontains=query) |
                Q(author__first_name__icontains=query) |
                Q(category__name__icontains=query)
            )
        else:
            object_list = self.model.objects.all()
        return object_list

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['now'] = timezone.now()
        context.update(self.extra_context)
        return context

class BookDetails(DetailView):
    model = Book
    template_name = 'books/book_details.html'
    extra_context = {
        'category_list': Category.objects.all(),
        'author_list': Author.objects.all(),
        'language_list': Language.objects.all(),
    }

    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)
        context['now'] = timezone.now()
        context.update(self.extra_context)
        print(context)
        return context

base.html

<form class="example" action="" style="margin:auto;max-width:300px">
  <input type="text" name='q' placeholder="Search...">
  <button type="submit" value='{{ request.GET.q }}'><i class="fa fa-search"></i></button>
</form><br>

在这里,BookList 视图是我的主页,当我从这里搜索时,它运行良好,但当我进入详细信息页面时,它就不起作用了。因为 BookDetailView 我没有在 base.html 模板中发送任何类型的查询。那么,在这种情况下,我如何从 DetailView 发送查询,或者是否有任何用于 DetailView 的内置装饰器,或者我可以只使用一个可用于动态搜索所有模板的类?

谢谢

【问题讨论】:

    标签: python django search django-class-based-views


    【解决方案1】:

    您需要在表单中指定BookList 视图的url:

    <form class="example" action="{% url "the name of your route for the BookList" %}" style="margin:auto;max-width:300px">
    

    【讨论】:

    • 非常感谢伯恩哈德·瓦兰特。对我来说效果很好。
    猜你喜欢
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多