首页 > 解决方案 > Auto select value from dropdown list when editing existing value - flask pusher

问题描述

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.

标签: python-3.xflaskdropdownpusher

解决方案


您应该使用 WTForms 而不是自己构建此表单。它有一个内置的SelectField。完成此操作后,您将能够在定义表单的位置(如果选项是静态的)或有问题的视图(update_record此处)中填充选项。例子:

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)

不要忘记{{ form.hidden_tag() }}在表单内的模板中使用。这将为您提供CSRF 保护,这是您目前的表格所没有的。

而且,backend.html似乎update.html几乎相同。为这些使用单个文件应该不难。例如:

{% 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 %}

推荐阅读