Home > other >  Flask how to set HTML dropdown selected value based on current choice
Flask how to set HTML dropdown selected value based on current choice

Time:10-10

I have a page in my Flask app where the user can query the last 10, 25, 50, or 100 entries of a table. I want the dropdown default selection to display the number of entries that the user has chosen. So if they decided that they want to display 50 entries, the option 50 would be selected in the dropdown menu.

I think I'm close, but my code below isn't doing what I'm aiming for:

app.py:

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

@app.route('/history', methods=['GET'])
def history():
    if not request.args.get('log'):
        query_limit = "10"
    else:
        query_limit = request.args.get('log')

    log = log_db.query.order_by(log_db.id.desc()).limit(query_limit).all()
    return render_template('history.html', log=log)

history.html:

<form >
    <label for="log">Number of change log entries to query:</label>
    <select name="log" id="log_query">
        <option value="10" 
        {% if query_limit == 10 %} selected {% endif %}>10</option>
        <option value="25" 
        {% if query_limit == 25 %} selected {% endif %}>25</option>
        <option value="50" 
        {% if query_limit == 50 %} selected {% endif %}>50</option>
        <option value="100" 
        {% if query_limit == 100 %} selected {% endif %}>100</option>
    </select><br><br>
    <input type="submit" value="Update View" >
</form>

CodePudding user response:

In your render_template return you are not passing the "query_limit". Take care with compare string and integers it could not work.

CodePudding user response:

I edited the code and got it to work. I passed query_limit to history.html and put quotes around each number in the select tag.

app.py

@app.route('/history', methods=['GET'])
def history():
    if not request.args.get('log'):
        query_limit = "10"
    else:
        query_limit = request.args.get('log')

    log = log_db.query.order_by(log_db.id.desc()).limit(query_limit).all()
    return render_template('history.html', log=log, query_limit=query_limit)

history.html

<form >
    <label for="log">Number of change log entries to query:</label>
    <select name="log" id="log_query">
        <option value="10" 
        {% if query_limit == "10" %} selected {% endif %}>10</option>
        <option value="25" 
        {% if query_limit == "25" %} selected {% endif %}>25</option>
        <option value="50" 
        {% if query_limit == "50" %} selected {% endif %}>50</option>
        <option value="100" 
        {% if query_limit == "100" %} selected {% endif %}>100</option>
    </select><br><br>
    <input type="submit" value="Update View" >
</form>
  • Related