Modify query parameters in current GET request for new url

Question:

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?

Asked By: stpk

||

Answers:

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 werkzeug.urls import url_encode

@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, url_encode(args))
<a href="{{ modify_query(b=2) }}">Link with updated "b"</a>
Answered By: davidism

Directly in Jinja:

{% set args = request.args.copy() %}
{% set _ = args.setlist("b", [2]) %}
{{ url_for(request.endpoint, **args) }}
Answered By: Neil McGuigan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.