Login

Add GET parameter tag

Author:
marltu
Posted:
July 12, 2010
Language:
Python
Version:
1.2
Score:
3 (after 3 ratings)

This is custom tag I wrote for myself for solving situations when you have filter form and page numbers in the same page. You want to change ?page=.. or add it if it doesn't exist to save filter form data while moving through pages.

Usage: place this code in your application_dir/templatetags/add_url_parameter.py In template: {% load add_get_parameter %} <a href="{% add_get_paramater param1='const_value',param2=variable_in_context %}"> Link with modified params </a>

It's required that you have 'django.core.context_processors.request' in TEMPLATE_CONTEXT_PROCESSORS

URL: http://django.mar.lt/2010/07/add-get-parameter-tag.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from django import template

from django.template import Library, Node, resolve_variable, TemplateSyntaxError
from django.template import Context, Template, Node, resolve_variable, TemplateSyntaxError, Variable

register = template.Library()


"""
This is custom tag I wrote for myself for solving situations when you have filter form and page
numbers in the same page. You want to change ?page=.. or add it if it doesn't exist to save
filter form data while moving through pages.

Usage: place this code in your application_dir/templatetags/add_get_parameter.py
In template: 
{% load add_get_parameter %}
<a href="{% add_get_paramater param1='const_value',param2=variable_in_context %}">
    Link with modified params
</a>

It's required that you have 'django.core.context_processors.request' in TEMPLATE_CONTEXT_PROCESSORS

URL: http://django.mar.lt/2010/07/add-get-parameter-tag.html
"""


class AddGetParameter(Node):
    def __init__(self, values):
        self.values = values
        
    def render(self, context):
        req = resolve_variable('request',context)
        params = req.GET.copy()
        for key, value in self.values.items():
            params[key] = Variable(value).resolve(context)
        return '?%s' %  params.urlencode()


@register.tag
def add_get_parameter(parser, token):
    from re import split
    contents = split(r'\s+', token.contents, 2)[1]
    pairs = split(r',', contents)
    
    values = {}
    
    for pair in pairs:
        s = split(r'=', pair, 2)
        values[s[0]] = s[1]    
    
    return AddGetParameter(values)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks 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, 6 months ago

Comments

Please login first before commenting.