How do you create a Jinja list and collect a Jinja list in the flask app?

Question:

I can make a list and get it, but it only gives me one of those items in the list, if I try to get any others outside of the first index I get the list index out of range exception

The list I’ve tried to make (the only thing I’ve found online).

{% set infoList = [1,2] %}
<form method="post"><button name="add_to_collection" value={{infoList}}>{{collection[0]}}</button></form>

The way I’ve tried to collect the list

information = request.form.getlist('information')

When I try to get both indexes 0 & 1, I get List Out Of Index Range, I can only get the first.
If I print out that list, this is the output

[1,

not sure how this works and couldn’t find it online anywhere.

Asked By: corieleclair

||

Answers:

You should enclose the attributes in quotes. If you also pass the values of the list separated by commas, it is easy to query the values on the server side and to convert the type.

{% set info_list = [1,2] %}
<form method="post">
    <button name="info" value="{{info_list | join(',')}}">Submit</button>
</form>
info = request.form.get('info', type=lambda x: [int(t) for t in x.split(',')])
Answered By: Detlef

The problem is that you need to escape the comma. If you inspect the button you’ll see this:

<button name="add_to_collection" value="[1," 2]="">text here</button>

Here, it thinks you’re adding two things to the html. I’m honestly not sure if you can set an input value as a list.

Try this:

{% set infoList = "[1,2]" %}

or this:

<button name="add_to_collection" value="{{ infoList }}">{{collection[0]}}</button>

or even this if the list never changes:

<button name="add_to_collection" value="[1,2]">{{collection[0]}}</button>

and then deal with turning it back into a list when you’re in the backend.

Answered By: scoofy
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.