Created
October 18, 2016 22:22
-
-
Save UplandsDynamic/f4f2ea56b889b7fddfae47163371c2c9 to your computer and use it in GitHub Desktop.
Function for Python Django to update request.GET parameters, retaining all existing parameters, with a given parameter added or updated.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def update_url_param(request, param_name): | |
# function to update request.GET params, retaining all existing params, with param_name added or updated. | |
existing_params = dict(request.GET) # convert immutable querydict to mutable dict | |
if not existing_params: | |
return '?{}='.format(param_name) | |
else: # if existing params | |
existing_str = '' | |
existing_params.pop(param_name, None) # pop off existing param_name if exists | |
for p, v in existing_params.items(): | |
existing_str += '{}{}&'.format(p, '={}'.format(v[0]) if v[0] else '') | |
return '?{}{}='.format(existing_str, param_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use at your own risk. Works for my current needs, but not extensively tested.