Search code examples
pythondjangosearchelasticsearchdjango-haystack

How to display search results(django+haystack+elasticsearch) on the SAME page?


I included haystack+elasticsearch into my django project folowing by official haystack docs. Searching is working good, but results are displaying in separate page (search.html).I need show searching results on the same page I place searching query from. I include search template into my base.html like this: {% include 'search/search.html' %} My templates are in different dirs:templates/students/base.html and templates/search/search.html. As far I understand haystack uses its own /search/search.html for displaying search results. Which way can I change that behavior, how to display results on the same page? Please help!

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()

Solution

  • You can create a custom view and use that in your templates:

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

    and in your urls.py:

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

    and in your templates, just call this view in your form:

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