Home » Django » How do i pass GET parameters using django urlresolvers reverse

How do i pass GET parameters using django urlresolvers reverse

Posted by: admin November 30, 2017 Leave a comment

Questions:

i am using django 1.2 and going from one view to another using the urlresolvers reverse method.

url = reverse(viewOne)

and i want to pass a get parameter, for example

name = ‘joe’

so that in the viewOne if i do

def viewOne(request):
    request.GET['name']

i will get

joe

how do i do that ?

Answers:

GET parameters have nothing to do with the URL as returned by reverse. Just add it on at the end:

url = "%s?name=joe" % reverse(viewOne)

Questions:
Answers:

A safer and more flexible way:

import urllib
from django.core.urlresolvers import reverse

def build_url(*args, **kwargs):
    get = kwargs.pop('get', {})
    url = reverse(*args, **kwargs)
    if get:
        url += '?' + urllib.urlencode(get)
    return url

then you can use build_url:

url = build_url('view-name', get={'name': 'joe'})

which takes same arguments as reverse, but provides an extra keyword argument get where you can put your GET parameters in it as a dictionary.

Questions:
Answers:

This is very similar to Amir’s solution but handles lists as well.

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

def build_url(*args, **kwargs):
    params = kwargs.pop('params', {})
    url = reverse(*args, **kwargs)
    if not params: return url

    qdict = QueryDict('', mutable=True)
    for k, v in params.iteritems():
        if type(v) is list: qdict.setlist(k, v)
        else: qdict[k] = v

    return url + '?' + qdict.urlencode()

Example usage:

>>> build_url('member-list', params={'format': 'html', 'sex': ['male', 'female']})
u'/members/?format=html&sex=male&sex=female'

Questions:
Answers:

Sorry for the delayed correction on this.

While both the answers here handles the required task too well, i think just a simple function to urlencode a dictionary is the most flexible way of doing this:

import urllib

def getify(dic):
    st = ''
    for K, V in dic.items():
        K = urllib.parse.quote(str(K))
        if isinstance(V, list):
            for v in V:
                st += K + '=' + urllib.parse.quote(str(v)) + '&'
        else:
            st += K + '=' + urllib.parse.quote(str(V)) + '&'
    return st.rstrip('&')