Search code examples
pythondjangodjango-haystack

Django-Haystack Faceting Initial Set up


Haystack 2.4.1 (Django 1.9)

I’m having trouble with faceted search.

I tried to follow the example from this recent Stack Overflow answer, but it still isn't working.

From a Searchapp

#search/views.py
from django.shortcuts import render
from haystack.forms import FacetedSearchForm
from haystack.generic_views import FacetedSearchView as BaseFacetedSearchView

class FacetedSearchView(BaseFacetedSearchView):
        form_class = FacetedSearchForm
        facet_fields = ['categories']
    template_name = 'search/search.html'
    context_object_name = 'page_object'

#urls.py
from haystack.forms import FacetedSearchForm
from search.views import FacetedSearchView
from haystack.query import SearchQuerySet

urlpatterns += patterns('haystack.views',
    url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'),
)

I’d appreciate any help you guys can provide. I’m at my wits end on this one.

I am using the template from the Haystack documentation.

{% if query %}
    <!-- Begin faceting. -->
    <h2>By Category</h2>

    {{ self.get_facets }}

    <div>
        <dl>
            {% if facets.fields.category %}
                <dt>category</dt>
                {# Provide only the top 5 categories #}
                {% for category in facets.fields.categories|slice:":5" %}
                    <dd><a href="{{ request.get_full_path }}&amp;selected_facets=category_exact:{{ category.0|urlencode }}">{{ category.0 }}</a> ({{ category.1 }})</dd>
                {% endfor %}
            {% else %}
                <p>No category facets.</p>
            {% endif %}
        </dl>
    </div>
    <!-- End faceting -->

    <!-- Display results... -->
    {% for result in page_object %}
        <div class="search_result">
            <h3><a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a></h3>

            <p>{{ result.object.body|truncatewords:80 }}</p>
        </div>
    {% empty %}
        <p>Sorry, no results found.</p>
    {% endfor %}

{% endif %}

Solution

  • Page is not in context. Use object_list directly to access the objects.

    Otherwise, if you want to follow along the websites official tutorial, just use this in your urls.py:

    url(r'^search/', FacetedSearchView(form_class=FacetedSearchForm, searchqueryset = SearchQuerySet().facet('author')), name='haystack_search)
    

    instead of :

    url(r'^search/', FacetedSearchView(form_class=FacetedSearchForm, selected_facets=['author'] , name='haystack_search).
    

    Hope this helps sombody :)