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'...)
This should work:
get = request.GET.copy()
del get['b']
params = urllib.urlencode(get)
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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With