Maintain existing query string in paginator links.

This commit is contained in:
Christopher Charbonneau Wells 2017-11-18 07:33:32 -05:00
parent 4aa51e44da
commit 87e13661ee
2 changed files with 29 additions and 3 deletions

View File

@ -1,10 +1,12 @@
{% load babybuddy_tags %}
{% if is_paginated %}
<nav aria-label="Page navigation">
<ul class="pagination justify-content-center">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous">
<a class="page-link" href="{% relative_url 'page' page_obj.previous_page_number %}" aria-label="Previous">
<i class="icon icon-chevron-left" aria-hidden="true"></i>
<span class="sr-only">Previous</span>
</a>
@ -14,14 +16,14 @@
{% for num in page_obj.paginator.page_range %}
{% if num > page_obj.number|add:"-3" and num < page_obj.number|add:"3" %}
<li class="page-item{% if num == page_obj.number %} active{% endif %}">
<a class="page-link" href="?page={{ num }}">{{ num }}</a>
<a class="page-link" href="{% relative_url 'page' num %}">{{ num }}</a>
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label="Next">
<a class="page-link" href="{% relative_url 'page' page_obj.next_page_number %}" aria-label="Next">
<i class="icon icon-chevron-right" aria-hidden="true"></i>
<span class="sr-only">Next</span>
</a>

View File

@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def relative_url(context, field_name, value):
"""
Create a relative URL with an updated field value.
:param context: current request content.
:param field_name: the field name to update.
:param value: the new value for field_name.
:return: encoded relative url with updated query string.
"""
url = '?{}={}'.format(field_name, value)
querystring = context['request'].GET.urlencode().split('&')
filtered_querystring = filter(
lambda p: p.split('=')[0] != field_name, querystring)
encoded_querystring = '&'.join(filtered_querystring)
return '{}&{}'.format(url, encoded_querystring)