[Fixed]-Pass a query parameter with django reverse?

13👍

It depends on whether you are building the URL in the python code or in a template.

In python code (e.g. the view):

from django.http import QueryDict

query_dictionary = QueryDict('', mutable=True)
query_dictionary.update(
    {
        'tag': 'food'
    }
)
url = '{base_url}?{querystring}'.format(
    base_url=reverse(my.url.name),
    querystring=query_dictionary.urlencode()
)

And in a template:

<a href="{% url 'my.url.name' %}?tag=food">My Link</a>

You caould also pass the QueryDict object from the view to the template and use that when building the URL in the template:

<a href="{% url 'my.url.name' %}?{{ query_dictionary.urlencode }}">My Link</a>

7👍

Django’s reverse does not include GET or POST parameters. They are not part of the url.

You can of course always create the url by, for instance in a template, attaching the parameter as in:

{% url 'named_url' %}?tag=food

This way it gets attached anyway. Alternative is building an url regex that includes the possible tag, like:

url(r'^/people/raj/updates/(?P<tag>[a-zA-Z0-9]+/)?', yourview())

This way you can check for the kwarg tag in your view.

Leave a comment