Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, exclude parameters from request.GET

What's the best way to exclude parameters from request.GET?

eg, given a url param ?a=a&b=b&c=c and I want to take out param b to generate url param to ?a=a&c=c without changing request.GET

Right now I am looping through the keys to take out b

params = {}
for key,value in request.GET.items():
  if not key == 'b':
    params[key] = value

url = urllib.urlencode(params)

I am wondering if there is a better, more elegant way to achieve the same result? eg.

request.GET.urlencode(exclude=['b',])

or even this, better

urllib.urlencode(request.GET.exclude('b'...)
like image 439
James Lin Avatar asked Aug 31 '12 01:08

James Lin


3 Answers

This should work:

get = request.GET.copy()
del get['b']

params = urllib.urlencode(get)
like image 187
Sam Dolan Avatar answered Nov 04 '22 19:11

Sam Dolan


You cannot manipulate the request.GET directly because it is an immutable QueryDict. So make a shallow copy and then remove the desired key.

cp = request.GET.copy()
cp.pop('b')

params = urllib.urlencode(cp)
like image 2
thikonom Avatar answered Nov 04 '22 19:11

thikonom


All these answers almost got it right, but failed for the edge case where there are multiple parameters with the same key name, which is valid (and the whole reason why django uses a QueryDict and not a dict). If you use urllib's urlencode it will lose the extra parameters, you need to use the urlencode provided by QueryDict.

https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict

QueryDict is a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple="multiple">, pass multiple values for the same key.

So the correct way is:

querydict = request.GET.copy()
if 'b' in querydict:
    del querydict['b']
return querydict.urlencode()
like image 1
dalore Avatar answered Nov 04 '22 19:11

dalore