Thursday, 15 July 2010

Change a query string in Django? -



Change a query string in Django? -

i have requested page:

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

i want link page (unset type , foo relative previous):

example.com/stuff?stage=unpublished

and want conveniently like:

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

how do it? there inbuilt way, or library?

i utilize tedious

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

as david said, created own template tag. can phone call stuff {% urlgen a=1 b=2 %}. terser , neater.

@register.simple_tag(name = 'urlgen') def urlgen(**kwargs): with_present_values = dict( [ (k,v) k, v in kwargs.items() if v]) homecoming 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: homecoming '?' + query_dictionary.urlencode() else: homecoming ''

not covered here: registering template tags django.

django

No comments:

Post a Comment