Altering one query parameter in a url (Django)

I did this simple tag which doesn't require 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 your url GET string if it's not there, or replace it with the new value if it's already there.

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

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


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 a more comprehensive solution, use Zachary Voase's URLObject 2, which is very nicely done.

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