Search code examples
pythonhtmlflaskhtml-select

How to set default selection in Flask dropdown menu based on user's previous choice?


In my Flask application, I have a page that displays a table of log entries. On this page, I want to provide a dropdown menu that allows the user to select the number of entries to display (10, 25, 50, or 100), with the default selection being the value that the user has previously selected. I have written the following code, but the default selection in the dropdown menu is not working as expected:

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)

<form class="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" class="create_edit">
</form>

How can I modify my code to ensure that the dropdown menu shows the correct default selection based on the user's previous choice?


Solution

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