redirecting with url_for to a path with query params in flask

Question:

So let’s say I have a template with a couple of links, the links will be like this:

<a class='btn btn-primary' href='/?chart=new_chart&chart=other_chart'>View Summary</a>

However, most of the times when I have done links or included resources, I have used the following syntax:

<script src="{{ url_for('static', filename='some_silly_js') }}"></script>

is it possible to do a url_for with query parameters? Something like:

<a href="{{ url_for('stats', query_params={chart: [new_chart, other_chart]}) }}>View More</a>
Asked By: corvid

||

Answers:

Any extra keyword parameters passed to url_for() which are not supported by the route are automatically added as query parameters.

For repeated values, pass in a list:

<a href="{{ url_for('stats', chart=[new_chart, other_chart]) }}>View More</a>

Flask will then:

  1. find the stats endpoint
  2. fill in any required route parameters
  3. transform any remaining keyword parameters to a query string

Demo, with 'stats' being the endpoint name for /:

>>> url_for('stats', chart=['foo', 'bar'])
'/?chart=foo&chart=bar'
Answered By: Martijn Pieters

As per the documentation:

Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments.

I have tried this and it works as per the documentation

redirect(url_for('face_id_detail', faceid=faceid, name=faceidtag))

Note: faceid is the parameter in the method && name is not in the method parameters so it is appending to querystring.

The method signature for face_id_detail is:

@app.route('/faceids/<faceid>')
def face_id_detail(faceid):
    # the method code
Answered By: Gopal Singh Sirvi
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.