如何在Django中创建适用于我所有视图的搜索

时间:2016-02-18 01:37:23

标签: django full-text-search

我目前在base.html中有一个搜索字段。这是一个片段

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="{% url 'posts:list'  %}">HEHTS</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">


          <form method="GET" action=" "  class="navbar-form navbar-right">
            <div class="input-group">{% csrf_token %}
              <input type="text" name="q" id="search" placeholder="search" value="{{ request.GET.q }}" class="form-control"
              style="width: 350px">


            <!--<input type="text" name="q" placeholder="search post" value="{{ request.GET.q }}"/>-->
            <!--<input type="submit" value="Search" />-->
        <!--</form>-->

              <ul id="search-results">

              </ul>

            <span class="input-group-btn">
            <button type="submit" class="btn btn-primary"><span style="font-size:1.4em" class="glyphicon glyphicon-search"></span> </button>
            </span>
            </div>
          </form>

          <ul class="nav navbar-nav">
            <li><a href="{% url 'posts:list'  %}">Home</a></li>
            <!--<li><a href="#">Sewp</a></li>-->
            {% if user.is_authenticated %}
            <li><a href="{% url 'admin:index' %}">Admin</a></li>
            <li><a href="{% url 'posts:create' %}">Create</a></li>
            {% endif %}

          </ul>
        </div><!--/.nav-collapse -->
      </div>
</nav>

这在我的detail.html视图中不起作用。它仅适用于我的post_list.html视图,后面是两个视图

  def post_detail(request, slug=None):
        instance = get_object_or_404(Post, slug=slug)
        if instance.publish > timezone.now().date() or instance.draft:
            if not request.user.is_staff or not request.user.is_superuser:
                raise Http404

        queryset_list = Post.objects.active()
        query = request.GET.get("q")
        if query:
            queryset_list = queryset_list.filter(
                    Q(title__icontains=query) |
                    Q(content__icontains=query) |
                    Q(user__first_name__icontains=query) |
                    Q(user__last_name__icontains=query)
            ).distinct()


        share_string = quote_plus(instance.content)
        template = "posts/post_detail.html"
        context = {
            "instance": instance,
            "name": instance.title,
            "share_string": share_string,
            "queryset_list": queryset_list
        }
        return render(request, template, context)


    def post_list(request):
        today = timezone.now().date()
        queryset_list = Post.objects.active()
        if request.user.is_staff or request.user.is_superuser:
            queryset_list = Post.objects.all()

        query = request.GET.get("q")
        if query:
            queryset_list = queryset_list.filter(
                    Q(title__icontains=query) |
                    Q(content__icontains=query) |
                    Q(user__first_name__icontains=query) |
                    Q(user__last_name__icontains=query)
            ).distinct()
        paginator = Paginator(queryset_list, 8)
        page_request_var = 'page'
        page = request.GET.get(page_request_var)
        try:
            queryset = paginator.page(page)
        except PageNotAnInteger:
            queryset = paginator.page(1)
        except EmptyPage:
            queryset = paginator.page(paginator.num_pages)
        template = "posts/post_list.html"
        name = "user"
        context = {
            "object_list": queryset,
            "name": name,
            "page_request_var": page_request_var,
            "today": today,
        }
        return render(request, template, context)

我想要的结果是保持DRY并且只需要编写一次代码并且能够在我的base.html中使用它,无论我渲染什么视图它都能工作。 我该怎么做,所以我的博客应用程序可以在任何视图中工作?欢迎提供所有帮助或建议。

1 个答案:

答案 0 :(得分:1)

我认为这可能很容易。只需给搜索一个专用的查看功能和相应的网址,我们就说:

url(r'^post-search/$', views.post_search, name='post-search')

然后,您将当前的搜索表单放在base.html中,并更改表单的操作,指向post-search网址:

<form method="GET" action="{% url 'post-search' %}"  class="navbar-form navbar-right">
    <!-- same content goes here -->
</form>

所以现在每次提交此表单时,总是会执行视图函数post_search并执行相同的过程并显示结果。

Some explanations about form action attribute