【问题标题】:How to display search results(django+haystack+elasticsearch) on the SAME page?如何在同一页面上显示搜索结果(django+haystack+elasticsearch)?
【发布时间】:2015-11-26 11:58:35
【问题描述】:

按照官方 haystack 文档,我将 haystack+elasticsearch 包含到了我的 django 项目中。搜索效果很好,但结果显示在单独的页面(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()

【问题讨论】:

    标签: python django search elasticsearch django-haystack


    【解决方案1】:

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

    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' %}">
    

    【讨论】:

    • 贾洪吉尔,感谢您的回复!这里的“custom_search”是什么?模板名称?请提供更多详细信息。
    • @AndriyKravchenko, custom_search 是网址的名称。这就是 django 处理 url 的方式。也就是说,您可以优雅地说“module_name:view_name”,而不是写像/path/to/view 这样的url。阅读更多here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 2022-01-18
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    相关资源
    最近更新 更多