How do I populate a select tag with Flask?

后端 未结 1 1127
夕颜
夕颜 2021-02-06 06:52

I am trying to access a list of JSON objects (from mongo) in python to populate a dropdown list using flask templates. Subsequently, I need to access the selected item. I am h

相关标签:
1条回答
  • 2021-02-06 06:55

    There are a few things wrong here:

    First, when you call render_template('chooser.html'), you are never passing any arguments to the template rendering process. By default, Jinja2 does not error out if an attribute your reference is not found, so you get no error message. Basically, for the code in your template that looks like this:

    {% for o in option_list %}
        ....
    {% endfor %}
    

    The innards of this for loop are never rendered because you never specify what option_list is. In this case, Jinja2 will just default it to an empty string, and then you are essentially looping over the characters of the empty string (which of course means the innards of the for-loop are never run).

    So, you need to specify the template what the value of option_list is:

    return render_template('chooser.html', option_list=option_list)
    

    The other issue is that your HTML is going to be messed up due to where you've put your for loop:

    <select name="option" width="300px">
    {% for o in option_list %}
        <option value="{{ o.optid }}" SELECTED>{{ o.optid }}</option>
        </select>
    </td>
    <td>
        <input class="button1" type="submit" value="Select">
    </td>
    {% endfor %}
    

    I think you wanted to do the following:

    <select name="option" width="300px">
    {% for o in option_list %}
        <option value="{{ o.optid }}" SELECTED>{{ o.optid }}</option>
    {% endfor %}
    </select>
    </td>
    <td>
        <input class="button1" type="submit" value="Select">
    </td>
    

    See the rendering part of the tutorial, or the Jinja2 documentation for more info.

    0 讨论(0)
提交回复
热议问题