自定义动态烧瓶WTForm

时间:2019-02-26 08:25:18

标签: sqlite flask jinja2 flask-wtforms

我正在尝试构建WTForm,以将元素添加到SQLite表中。该表只有两个列(id和name)

routes.py:

@app.route('/systems', methods=['GET', 'POST'])

def systems():

    form = SystemForm()
    if form.validate_on_submit():
        system = Systems(name=form.systemname.data)
        db.session.add(system)
        db.session.commit()
        return redirect(url_for('systems'))
    return render_template('systems.html', title='Systems', form=form)

forms.py:

class SystemForm(FlaskForm):

    systemname = StringField('System', validators=[DataRequired()])
    submit = SubmitField('Add')

但是在表单之前,我想显示表中已经存在的所有行:

  • 系统1
  • 系统2 ....

    文本字段/提交按钮

假设我可以通过以下方式抓取行,我该如何做到这一点:

database = "mydb.db"
conn = create_connection(database)
cur = conn.cursor()

cur.execute("SELECT * FROM systems")
data = cur.fetchall()

列表是否将成为表单定义的一部分?或可以将其放置在form标记之前,如下所示(对sqlite查询返回的行进行数据处理):

    {% for item in data %}
        <table>
        <tr>
            <td>{{item[1]}}</td>
        </tr>
        </table>
    {% endfor %}

如何将数据传递到html模板?

2 个答案:

答案 0 :(得分:0)

看来您已经做完了所有事情,唯一要做的就是

@app.route('/systems', methods=['GET', 'POST'])
def systems():
    form = SystemForm()
    if form.validate_on_submit():
        system = Systems(name=form.systemname.data)
        db.session.add(system)
        db.session.commit()
        return redirect(url_for('systems'))
    # perform your database lookup to get `data`
    return render_template('systems.html', title='Systems', form=form, data=data)

答案 1 :(得分:0)

@app.route('/systems', methods=['GET', 'POST'])

def systems():
    if request.method == 'POST':
        if request.form.get('submit') == 'Add':
            form = SystemForm()
            if form.validate_on_submit():
                system = Systems(name=form.systemname.data)
                db.session.add(system)
                db.session.commit()
                return redirect(url_for('systems'))
        else:
            delete_ids = request.form.getlist('delete_id')
            for delete_id in delete_ids:
                db.session.query(Systems).filter(Systems.id==delete_id).delete()
            db.session.commit()

    data = db.session.query(Systems)
    form = SystemForm()
    return render_template('systems.html', title='Systems', form=form, data=data)