Home > Mobile >  Flask how to specify a default value for select tag HTML
Flask how to specify a default value for select tag HTML

Time:10-10

I have an app that tracks truck appointments. In this app I have a list of carriers in a db table. When the user wants to update an appointment, they can choose a new carrier from the list of carriers in the db using a dropdown menu. How can I set the dropdown default value to be the current carrier selection?

Here's what I tried so far (without any luck):

app.py:

class carriers_db(db.Model):
    carrier_id = db.Column(db.Integer, primary_key=True)
    carrier_name = db.Column(db.String(100), nullable=False)

class appts_db(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    carrier = db.Column(db.String(100), nullable=False)

@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    appt = appts_db.query.get_or_404(id)
    carriers = carriers_db.query.order_by(carriers_db.carrier_name).all()

update.html:

<h4>Current carrier: {{ appt.carrier }}</h4>
<label>Option to select a new carrier:</label><br>
<select name="carrier">
    {% for carrier in carriers %}
        <option 
        value = "{{ carrier.carrier_name }}"
        selected = "{{ carrier.carrier_name }}">
        {{ carrier.carrier_name }}</option>
    {% endfor %}
</select>

CodePudding user response:

You can add a check if the value is equal to the selected value in the for loop in update.html:

update.html:

<h4>Current carrier: {{ appt.carrier }}</h4>
<label>Option to select a new carrier:</label><br>
<select name="carrier">
    {% for carrier in carriers %}
        <option
        value = "{{ carrier.carrier_name }}"
        {% if carrier.carrier_name == appt.carrier %} selected {% endif %}>
        {{ carrier.carrier_name }}</option>
    {% endfor %}
</select>

A full example to show selected option value in Jinja template:

app.py:

from flask import Flask, render_template, flash, url_for, request, redirect

app = Flask(__name__)
app.secret_key = b'a secret key'


@app.route('/update', methods=['GET', 'POST'])
def show_update():
    current_carrier = "tello"
    carriers = [{"carrier_name": "mint"},
                {"carrier_name": "tmobile"},
                {"carrier_name": "tello"}]
    return render_template('update.html', current_carrier=current_carrier,
                           carriers=carriers)

update.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Update page</title>
</head>
<body>
<h4>Current carrier: {{ current_carrier }}</h4>
<label>Option to select a new carrier:</label><br>
<select name="carrier">
    {% for carrier in carriers %}
    <option value="{{ carrier.carrier_name }}" {% if carrier.carrier_name== current_carrier %} selected {% endif %}>
        {{ carrier.carrier_name }}
    </option>
    {% endfor %}
</select>
</body>
</html>

Output:

flask selected option page

  • Related