Jesvin Jose
Jesvin Jose

Reputation: 23098

Change a query string in Django?

I have requested the page:

example.com/stuff?&type=2&foo=bar&stage=unpublished

I want a link to the page (unset type and foo relative to previous):

example.com/stuff?stage=unpublished

And I want to do it conveniently like:

<a href=?{% url_params_now with foo=None type=None %}">go up</a>

How do I do it? Is there some inbuilt way, or some library?


I use the tedious

{{url}}?{% if type %}type={{type}}{% endif %}&{% if foo %}foo={{foo}}{% endif %}&{% if stage %}stage={{stage}}{% endif %}

Upvotes: 1

Views: 85

Answers (2)

Jesvin Jose
Jesvin Jose

Reputation: 23098

As David said, I created my own template tag. I can call stuff like {% urlgen a=1 b=2 %}. its terser and neater.

@register.simple_tag(name = 'urlgen')
def urlgen(**kwargs):
    with_present_values = dict( [ (k,v) for k, v in kwargs.items() if v])
    return query_string_from_dict( with_present_values)

and

from django.http import QueryDict
def query_string_from_dict( dic):
    query_dictionary = QueryDict('', mutable=True)
    query_dictionary.update( dic)
    if dic:
        return '?' + query_dictionary.urlencode()
    else:
        return ''

Not covered here: registering template tags with Django.

Upvotes: 1

Alex Parakhnevich
Alex Parakhnevich

Reputation: 5172

Consider this approach:

{{url}}?type={{type|default:""}}&foo={{foo|default:""}}&stage={{stage|default:""}}

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#default

Also there is a built in default_if_none filter.

Upvotes: 0

Related Questions