Login

Add querystring parameters to path (template tag)

Author:
spenoir
Posted:
January 23, 2013
Language:
Python
Version:
1.4
Tags:
template templatetag pagination request querystring query-string
Score:
3 (after 3 ratings)

<h3>Page: {{ page.number }} of {{ page.paginator.num_pages }}</h3> {% if page.has_previous or page.has_next %} <div> {% if page.has_previous %} <a href="{% url_add_query page=page.previous_page_number %}">{% endif %}&laquo; Previous {% if page.has_previous %}</a>{% endif %} | {% if page.has_next %} <a href="{% url_add_query page=page.next_page_number %}">{% endif %} Next &raquo;{% if page.has_next %}</a>{% endif %} </div> {% endif %}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@register.simple_tag(takes_context=True)
def url_add_query(context, **kwargs):
    request = context.get('request')

    get = request.GET.copy()
    get.update(kwargs)

    path = '%s?' % request.path
    for query, val in get.items():
        path += '%s=%s&' % (query, val)

    return path[:-1]

More like this

Comments

kerridge0 (on April 9, 2013):
<p>Lovely, worked for me when I had filtered querysets with class base views:</p> <pre>{% if is_paginated %} {% load getpages_tags %} <div class="pagination"> <ul> {% if page_obj.has_previous %} <li> <a href="{% url_add_query page=page_obj.previous_page_number %}">Previous</a> </li> {% endif %} {% for pg in paginator.page_range %} {% if page_obj.number == pg %} <li class="active"> <a href="{% url_add_query page=pg %}">{{ pg }}</a> </li> {% else %} <li> <a href="{% url_add_query page=pg %}">{{ pg }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li> <a href="{% url_add_query page=page_obj.next_page_number %}">Next</a> </li> {% endif %} </ul> </div> {% endif %} </pre>

#

Please login first before commenting.