Search code examples
pythonurlflaskjinja2

Modify query parameters in current GET request for new url


I access a page with the path /mypage?a=1&b=1&c=1. I want to create a link to a similar url, with some parameters changed: /mypage?a=1&b=2&c=1, b changed from 1 to 2. I know how to get the current arguments with request.args, but the structure is immutable, so I don't know how to edit them. How do I make a new link in the Jinja template with the modified query?


Solution

  • Write a function that modifies the current url's query string and outputs a new url. Add the function to the template globals using your Flask app's template_global decorator so that it can be used in Jinja templates.

    from flask import request
    from urllib.parse import urlencode
    
    @app.template_global()
    def modify_query(**new_values):
        args = request.args.copy()
        
        for key, value in new_values.items():
            args[key] = value
    
        return '{}?{}'.format(request.path, urlencode(args))
    
    <a href="{{ modify_query(b=2) }}">Link with updated "b"</a>