Auto select value from dropdown list when editing existing value - flask pusher

Viewed 1075

I have created a website based on the 'Build A Live Table Using Flask' with pusher from this example: https://pusher.com/tutorials/live-table-flask

Everything is working fantastic with the exception of one thing. For a few of my values instead of having the user enter their own value I am using a dropdown list of values for them to select between. When they go to edit the entry, all values are remembered except this which is changing back to the default value. I need a way for this value to be remembered and selected when they go to edit the part.

Code used to create/edit job (same for both html)

backend.html

    {% extends 'base.html' %}

    {% block content %}

        <form method="POST" id="target"> 
            <div class="form-group">
                <input type="text" class="form-control" name="work" placeholder="Work No">
            </div>
            <div class="form-group">
                <label for='opt'>Choose Option</label>
                <select name='opt'>
                    <option value='Option 1'>Option 1</option>
                    <option value='Option 2'>Option 2</option>
                    <option value='Option 3'>Option 3</option>
                    <option value='Option 4'>Option 4</option>
                </select>
            </div>
            <button type="submit" class="btn btn-block btn-primary">Submit</button>
        </form>
    {% endblock %}

update.html

    {% extends 'base.html' %}

    {% block content %}

        <form method="POST" id="target"> 
            <div class="form-group">
                <input type="text" class="form-control" name="work" value="{{ data.work }}">
            </div>
            <div class="form-group">
                <label for='opt'>Choose Option</label>
                <select name='opt'>
                    <option value='Option 1'>Option 1</option>
                    <option value='Option 2'>Option 2</option>
                    <option value='Option 3'>Option 3</option>
                    <option value='Option 4'>Option 4</option>
                </select>
            </div>
            <button type="submit" class="btn btn-block btn-primary">Submit</button>
        </form>
    {% endblock %}

app.py

    from flask import Flask, request, jsonify, render_template, redirect
    import pusher
    from database import db_session
    from models import Work
    import os

    app = Flask(__name__)
    ...
    @app.route('/edit/<int:id>', methods=["POST", "GET"])
    def update_record(id):
        if request.method == "POST":
            work = request.form["work"]
            opt = request.form["opt"]

            update_work = Work.query.get(id)
            update_work.work = work
            update_work.opt = opt
            db_session.commit()

            data = {
                "id": id,
                "work": work,
                "opt": opt}
            pusher_client.trigger('table', 'update-record', {'data': data })
            return redirect("/active", code=302)
        else:
            new_work = Work.query.get(id)
            new_work.opt = new_work.opt     #do I need this?
            return render_template('update.html', data=new_work)

models.py

    from sqlalchemy import Column, Integer, String, DateTime
    from database import Base

    class Work(Base):
        __tablename__ = 'works'

        id = Column(Integer, primary_key=True)
        work = Column(String(50))
        opt = Column(String(120))

        def __init__(self, work=None, opt=None):
            self.work = work
            self.opt = opt

        def __repr__(self):
            return '<Work %r>' % (self.work)

Wanting to be able to edit entries and have the dropdown list auto select the correct option, not the default option, so when editing you don't have to reenter all the values again.

1 Answers

You should be using WTForms instead of building this form yourself. It has a built-in SelectField. Once you do that, you'll be able to populate the options either where the form is defined (if the options are static) or in the view in question (update_record here). Example:

from flask import request, redirect
from flask_wtf import FlaskForm
from wtforms import SelectField

from operator import itemgetter

class WorkForm(FlaskForm):
    opt = SelectField('Choose Option', coerce=int, choices=[(num, f"Option {num}") for num in range(1, 5)])
    # ... etc ...

@app.route('/edit/<int:id>', methods=["POST", "GET"])
def edit(id):
    form = WorkForm(request.form)

    if form.validate_on_submit():
        # Do things
        return redirect(url_for('active'), code=302)

    new_work = Work.query.get(id)
    opt_id = 0

    for choice in form.opt.choices:
        if choice[1] == new_work.opt:
            opt_id = choice[0]

    form.opt.data = opt_id
    return render_template('update.html', data=new_work)

Don't forget to use {{ form.hidden_tag() }} in the template inside your form. This will give you CSRF protection, which your present form doesn't have.

Also, backend.html and update.html seem to be nearly identical. It shouldn't be difficult to use a single file for these. E.g.:

{% if data is defined %}
<input type="text" class="form-control" name="work" value="{{ data.work }}">
{% else %}
<input type="text" class="form-control" name="work" placeholder="Work No">
{% endif %}
Related