搜索栏作为基本模板添加到一个类视图Django

时间:2019-01-28 15:06:44

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

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的内置装饰器,或者我可以仅使用一个可以动态搜索所有模板的类?

谢谢

1 个答案:

答案 0 :(得分:1)

您需要以以下形式指定BookList视图的网址:

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