Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a query parameter with django reverse?

Tags:

django

I have a url that is meant to be accessed like

/people/raj/updates
/people/raj/updates?tag=food

But Django reverse URL resolver seems to have no provision to do tag=food, that is to detect it as an extra parameter and put in the query string.

How do I pass query parameters?

like image 370
Jesvin Jose Avatar asked Sep 16 '14 09:09

Jesvin Jose


People also ask

How do I reverse in Django?

reverse() If you need to use something similar to the url template tag in your code, Django provides the following function: reverse (viewname, urlconf=None, args=None, kwargs=None, current_app=None)

How do I accept query parameters in Django?

We can access the query params from the request in Django from the GET attribute of the request. To get the first or only value in a parameter simply use the get() method. To get the list of all values in a parameter use getlist() method.

What is parameter in Django?

Url parameters can capture any part of a url, whether it's a string, a number or a special set of characters that has to be passed to a template or view method. Listing 2-4 illustrates two sets of django. urls. path and django.


2 Answers

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>
like image 104
hellsgate Avatar answered Sep 18 '22 15:09

hellsgate


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.

like image 36
Pan Pitolek Avatar answered Sep 19 '22 15:09

Pan Pitolek