1

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 %}
4
  • {% url %} with params doesn't help? docs.djangoproject.com/en/dev/ref/templates/builtins/#url Commented Nov 5, 2014 at 14:52
  • @danielfranca URL params are not bound to GET variables. Commented Nov 5, 2014 at 14:56
  • how about just ?stage=unpublished ? You dont need to explicitly set. Also, the best bet is to handle this in the view because nothing stops the user from sending arbitrary GET parameters as a part of the request. Commented Nov 5, 2014 at 14:59
  • Did you take a look to Django custom tags? docs.djangoproject.com/en/dev/howto/custom-template-tags Commented Nov 5, 2014 at 15:00

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good choice :) Cleaner than if/endif.. tags
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.