Login

Add querystring parameters to path (template tag)

Author:
spenoir
Posted:
January 23, 2013
Language:
Python
Version:
1.4
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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

kerridge0 (on April 9, 2013):

Lovely, worked for me when I had filtered querysets with class base views:

{% 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 %}

#

Please login first before commenting.