Changes between Initial Version and Version 1 of Ticket #10941, comment 27


Ignore:
Timestamp:
Jun 7, 2017, 7:28:50 AM (7 years ago)
Author:
Jimmy Merrild Krag

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #10941, comment 27

    initial v1  
    22
    33I have created two rather simple filter which allows you ro edit the query string. `django-spurl` already does some of this, however not very elegantly. I think the following three filters would be a great addition to Django that will get you "there" much of the time:
    4 {{{
    5 #!python
    6 import six
    7 from django import template
    8 import collections
    94
    10 from django.http import QueryDict
    11 
    12 register = template.Library()
    13 
    14 
    15 @register.simple_tag
    16 def build_query(**kwargs):
    17     """Build a query string"""
    18     query_dict = QueryDict(mutable=True)
    19 
    20     for k, v in kwargs.items():
    21         if isinstance(v, collections.Iterable) and not isinstance(v, six.string_types):
    22             query_dict.setlist(k, v)
    23         else:
    24             query_dict[k] = v
    25 
    26     return query_dict.urlencode()
    27 
    28 
    29 @register.simple_tag(takes_context=True)
    30 def set_query_values(context, **kwargs):
    31     """Override existing parameters in the current query string"""
    32     query_dict = context.request.GET.copy()
    33 
    34     for k, v in kwargs.items():
    35         if isinstance(v, collections.Iterable) and not isinstance(v, six.string_types):
    36             query_dict.setlist(k, v)
    37         else:
    38             query_dict[k] = v
    39 
    40     return query_dict.urlencode()
    41 
    42 
    43 @register.simple_tag(takes_context=True)
    44 def append_query_values(context, **kwargs):
    45     """Append to existing parameters in the current query string"""
    46     query_dict = context.request.GET.copy()
    47 
    48     for k, v in kwargs.items():
    49         if isinstance(v, collections.Iterable) and not isinstance(v, six.string_types):
    50             for v_item in v:
    51                 query_dict.appendlist(k, v_item)
    52         else:
    53             query_dict.appendlist(k, v)
    54 
    55     return query_dict.urlencode()
    56 }}}
     5[https://pastebin.com/vJ3feNvY]
    576
    587Usage is e.g. `<a href="?{% set_query_values page=page.next_page_number %}">&raquo;</a>` or `<a href="?{% append_query_values selected=item.id %}">Select {{ item.name }}</a>`
Back to Top