[Django]-Append a querystring to URL in django

40๐Ÿ‘

โœ…

Pass the query string in the template:

<a href="{% url 'my_videos' %}?filter=others&sort=newest">My Videos</a>
๐Ÿ‘คDavid542

16๐Ÿ‘

Iโ€™m not sure whether this was possible at the time of this question being asked, but if you have the data available to build the query string in your view and pass it as context, you can make use of the QueryDict class. After constructing it, you can just call its urlencode function to make the string.

Example:

    from django.http import QueryDict

    def my_view(request, ...):
        ...
        q = QueryDict(mutable=True)
        q['filter'] = 'other'
        q['sort'] = 'newest'
        q.setlist('values', [1, 2, 'c'])
        query_string = q.urlencode()
        ...

query_string will now have the value u'filter=other&sort=newest&values=1&values=2&values=c'

๐Ÿ‘คberuic

12๐Ÿ‘

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect


if my_videos:
    return HttpResponseRedirect( reverse('my_videos') + "?filter=others&sort=newest")
๐Ÿ‘คAhsan

5๐Ÿ‘

Here are two smart template tags for modifying querystring parameters within the template:

๐Ÿ‘คUdi

2๐Ÿ‘

In templates you could do something like the following:

{% url 'url_name' user.id %}
{% url 'url_name'%}?param=value
{% "/app/view/user_id" %}

In the first one, the querystring will be in the form of โ€œhttp://localhost.loc/app/view/user_idโ€
In the second one, the query string should be in the form of โ€œhttp://localhost.loc/app/view?param=valueโ€
In the third one, it is simple however I am recommending the first one which depends on the name of the url mappings applied in urls.py

Applying this in views, should be done using HttpResponseRedirect

    #using url_names
    # with standard querystring
    return HttpResponseRedirect( reverse('my_url') + "?param=value")
    #getting nicer querystrings
    return HttpResponseRedirect(reverse('my_url', args=[value]))
    # or using relative path
    return HttpResponseRedirect( '/relative_path' + "?param=value")

Hint: to get query string value from any other view

s = request.GET.get('param','')

1๐Ÿ‘

Redirect to the URL you want using HttpResponseRedirect

from django.http import HttpResponseRedirect

[...]

if my_videos:
    return HttpResponseRedirect(request.path + "?filter=others&sort=newest")
๐Ÿ‘คRoshan Mathews

Leave a comment