如何在SAME页面上显示搜索结果(django + haystack + elasticsearch)?

时间:2015-09-01 09:43:50

标签: python django search elasticsearch django-haystack

我在我的django项目中加入了haystack + elasticsearch,以及官方的haystack文档。搜索工作正常,但结果显示在单独的页面(search.html)。我需要在我放置搜索查询的同一页面上显示搜索结果。 我将搜索模板包含在我的base.html中,如下所示:{%include' search / search.html' %} 我的模板位于不同的目录:templates / students / base.html和templates / search / search.html。据我所知,haystack使用自己的/search/search.html来显示搜索结果。我可以通过哪种方式更改该行为,如何在同一页面上显示结果?请帮忙!

urls.py:

from django.conf.urls import patterns, include, url
from django.contrib import admin

from students.views.students import StudentUpdateView
from students.views.students import StudentDeleteView
from students.views.students import StudentAddView
from students.views.groups import GroupDeleteView
from students.views.journal import JournalView

urlpatterns = patterns('',

#haystack search url
    (r'^search/', include('haystack.urls')),

# main page url

    url(r'^$', 'students.views.students.students_list', name ='home'),

search.html:

<form method="get" action="">
 <table>
    {{ form.as_table }}
    <tr>
        <td>&nbsp;</td>
        <td>
              <input type="text" name="q">
              <button type="submit">Search</button>

        </td>
    </tr>
</table>
    {% for student in page.object_list %}
    <p><span style= "color:blue">Student:</
    span> {{ student.object.first_name }}&nbsp;{{student.object.last_name }}</p>

   <p>Ticket: {{ student.object.ticket }}</p>
   <p>Group: {{ student.object.student_group }}</p>

  {% empty %}
    <p>No results found.</p>
  {% endfor %}

seach_indexes.py:

from haystack import indexes
from students.models.students import Student

class StudentIndex(indexes.SearchIndex, indexes.Indexable):
    text             = indexes.CharField(document=True, use_template=True) 
    last_name     = indexes.CharField(model_attr='last_name')

    def get_model(self):
        return Student

    def index_queryset(self, using=None):       
        return self.get_model().objects.all()

1 个答案:

答案 0 :(得分:4)

您可以创建自定义视图并在模板中使用它:

class CustomSearchView(SearchView):
    template_name='/path/to/template.html'

和您的urls.py

urlpatterns = patterns('',
    url(r'^custom_search$', CustomSearchView.as_view(), name='custom_search'),
)

在您的模板中,只需在表单中调用此视图:

<form method="get" action="{% url 'search:custom_search' %}">