[FIXED] Flask – Setting Select field as selected in Jinja2


In a flask application i have a form where i want the user to be able to "update" the item in stock.
This is my route:

@app.route('/changepart/<ident>', methods=['GET', 'POST'])
def changepart(ident):

partToChange = dbs.query(Deler).filter(Deler.iddeler == ident)
placement = [(row.idplassering, row.plassering) for row in dbs.query(Plassering).all()]

return render_template('changepart.html',data=partToChange, select = placement)

The Deler table has a row indicating the placement of the part, and this corresponds to the "plassering" variable in the placement dataset.

In the template i am trying to get the value of the parts placement as preselected in the form.

{% if data %}
{% for item in data %}
<main class="container">
<form method="POST" action="">
    <div class="row">
    <div class="row">
        <div class="col-md-3">
            <div class="mb-3">
             <label class="form-label" for="plassering">Plassering</label>
                <select class="form-select" id="plassering" name="plassering">
                {% for option in select %}     
                    {% if option[0] == item.plassering %}
                        <option selected value="{{option[0]}}">{{option[1]}}</option>   
                        <option value="{{option[0]}}">{{option[1]}}</option>
                    {% endif %}      

The form displays all values from the placement dataset, but it does not set the matching ID’s as pre-selected.
Is there anyone that has any clue to what i am doing wrong?


I was able to solve this after some trial and error.
The error was in the variable comparison. Had to apply the filter below.

                {% if option[0]|int() == item.plassering|int() %}

Both variables are of type INT from the database, but comparison did not work without the int() filter.

Answered By – kincaid

Answer Checked By – Timothy Miller (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published