编辑现有值时从下拉列表中自动选择值-Flask Pusher

时间:2019-06-26 12:15:02

标签: python-3.x flask dropdown pusher

在以下示例中,我已经基于带有推送器的“使用烧瓶构建活动表”创建了一个网站:https://pusher.com/tutorials/live-table-flask

除一件事情外,所有事情都运转良好。对于我的一些值,而不是让用户输入自己的值,我使用值的下拉列表供他们选择。当他们去编辑条目时,所有值都将被记住,但此值会变回默认值。当他们去编辑零件时,我需要一种记住和选择此值的方法。

用于创建/编辑作业的代码(两个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)

希望能够编辑条目并让下拉列表自动选择正确的选项,而不是默认选项,因此编辑时不必再次输入所有值。

1 个答案:

答案 0 :(得分:0)

您应该使用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 protection,您目前的表单还没有。

此外,backend.htmlupdate.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 %}