DjangoDjango

Haystack Search Pager

Mar 06, 2014 · Updated: Jul 12, 2021 · by Tim Kamanin

To make haystack search pager place nicelly with other get parameters, we can do something like this:

  1. Create a templatetag:

    @register.simple_tag
    def get_search_pager_link(request):
        params = []
        link = "?"
        for key, value in request.GET.items():
            if key != "page":
                params.append(u"{}={}".format(key, value))
                link += "&".join(params)
            if len(link) > 1:
                link += "&"
        return link
    

  2. Use it in your search pager template like this:

    {% load core_tags %} {% if page.has_previous or page.has_next %}
    <ul class="pagination">
      {% if page.has_previous %}
      <li class="previous">
        <a
          href="{% get_search_pager_link request %}page={{ page.previous_page_number }}"
          >previous</a
        >
      </li>
      {% endif %} {% for pg in page.paginator.page_range %} {% if page.number == pg
      %}
      <li class="active">
        <a href="{% get_search_pager_link request %}page={{ pg }}">{{ pg }}</a>
      </li>
      {% else %}
      <li>
        <a href="{% get_search_pager_link request %}page={{ pg }}">{{ pg }}</a>
      </li>
      {% endif %} {% endfor %} {% if page.has_next %}
      <li class="next">
        <a
          href="{% get_search_pager_link request %}page={{ page.next_page_number }}"
          >next</a
        >
      </li>
      {% endif %}
    </ul>
    {% endif %}
    

That way we'll achieve some nice functionality: search pager will play well with other GET parameters.

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓