[ACCEPTED]-Altering one query parameter in a url (Django)-django-templates

Accepted answer
Score: 23

I did this simple tag which doesn't require 6 any extra libraries:

@register.simple_tag
def url_replace(request, field, value):

    dict_ = request.GET.copy()

    dict_[field] = value

    return dict_.urlencode()

Use as:

<a href="?{% url_replace request 'param' value %}">

It wil add 'param' to 5 your url GET string if it's not there, or 4 replace it with the new value if it's already 3 there.

You also need the RequestContext request 2 instance to be provided to your template 1 from your view. More info here:

http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/

Score: 18

So, write a template tag around this:

from urlparse import urlparse, urlunparse
from django.http import QueryDict

def replace_query_param(url, attr, val):
    (scheme, netloc, path, params, query, fragment) = urlparse(url)
    query_dict = QueryDict(query).copy()
    query_dict[attr] = val
    query = query_dict.urlencode()
    return urlunparse((scheme, netloc, path, params, query, fragment))

For 3 a more comprehensive solution, use Zachary 2 Voase's URLObject 2, which is very nicely done.

Note: The 1 urlparse module is renamed to urllib.parse in Python 3.

Score: 10

I improved mpaf's solution, to get request 1 directly from tag.

@register.simple_tag(takes_context = True)
def url_replace(context, field, value):
    dict_ = context['request'].GET.copy()
    dict_[field] = value
    return dict_.urlencode()
Score: 4

This worked pretty well for me. Allows 4 you to set any number of parameters in the 3 URL. Works nice for a pager, while keeping 2 the rest of the query string.

from django import template
from urlobject import URLObject

register = template.Library()

@register.simple_tag(takes_context=True)
def url_set_param(context, **kwargs):
    url = URLObject(context.request.get_full_path())
    path = url.path
    query = url.query
    for k, v in kwargs.items():
        query = query.set_param(k, v)
    return '{}?{}'.format(path, query)

Then in the 1 template:

<a href="{% url_set_param page=last %}">
Score: 1

There are a number of template tags for 4 modifying the query string djangosnippets.org:

http://djangosnippets.org/snippets/553/
http://djangosnippets.org/snippets/826/
http://djangosnippets.org/snippets/1243/

I 3 would say those are the most promising looking. One 2 point in all of them is that you must be 1 using django.core.context_processors.request in your TEMPLATE_CONTEXT_PROCESSORS.

Score: 0

In addition to the snippets mentioned by 4 Mark Lavin, Here's a list of other implementations 3 I could find for a Django template tag which 2 modifies the current HTTP GET query string.

On 1 djangosnippets.org:

On PyPI:

On GitHub:

More Related questions