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

20๐Ÿ‘

โœ…

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.

๐Ÿ‘คTom Christie

26๐Ÿ‘

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/

๐Ÿ‘คmpaf

10๐Ÿ‘

I improved mpafโ€™s solution, to get request 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()
๐Ÿ‘คwhncode

4๐Ÿ‘

This worked pretty well for me. Allows you to set any number of parameters in the URL. Works nice for a pager, while keeping 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 template:

<a href="{% url_set_param page=last %}">
๐Ÿ‘คallanberry

1๐Ÿ‘

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

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

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

๐Ÿ‘คMark Lavin

0๐Ÿ‘

๐Ÿ‘คIgor

0๐Ÿ‘

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

On djangosnippets.org:

On PyPI:

On GitHub:

๐Ÿ‘คakaihola

Leave a comment