这里是烧瓶初学者,请忍受我!在
在我为问题简化的这段代码中,我有一个定义的路由/有两个表单:我希望add表单向db添加内容,delete表单用于删除内容,简单。在
然而,我的问题是,在这段代码中,我无法区分哪个输入按钮和表单是按的格式添加验证()和formdel.验证()两者都始终返回true。在
如何区分按下哪个提交按钮以便相应地操作数据库?在
一开始我写了下面的注释,但是很明显它不起作用,因为validate方法返回true。。。。在
from flask import Flask, render_template, request
from flask.ext.sqlalchemy import SQLAlchemy
from wtforms import Form, StringField
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///botdb.db'
db = SQLAlchemy(app)
class BotFormAdd(Form):
botname = StringField('bot name')
botdescription = StringField('bot description')
class BotFormDelete(Form):
botid = StringField('bot id')
@app.route('/', methods=['GET', 'POST'])
def index():
formadd = BotFormAdd(request.form)
formdel = BotFormDelete(request.form)
if request.method == 'POST':
print(formadd.validate(), formdel.validate())
# if request.method == 'POST' and formadd.validate():
# print('in formadd')
# bot = Bot(name=formadd.botname.data, description=formadd.botdescription.data)
# db.session.add(bot)
# db.session.commit()
# return redirect(url_for('index'))
# if request.method == 'POST' and formdel.validate():
# print('in formdel')
# db.session.delete(formdel.botid.data)
# db.session.commit()
# return redirect(url_for('index'))
return render_template('index.html', title='Home', formadd=formadd, formdel=formdel)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>this is a test</title>
</head>
<body>
<form method=post action="/">
<dl>
{{ formadd.botname }}
{{ formadd.botdescription }}
</dl>
<p><input type=submit name='add' value='add this'>
</form>
<form method=post action="/">
<dl>
{{ formdel.botid }}
</dl>
<p><input type=submit name='delete' value='delete this'>
</form>
</body>
</html>
有很多方法可以做到这一点,但它可以分为两类,要么通过路由指明,要么通过表单上的元素来表示。在
大多数人只会添加单独的路线:
因此,您的删除表单将提交到该路由,得到处理并发送回索引。在
^{pr2}$你会有一个不同的方法来添加一个机器人。在
或者你可以从它的内容中检查它是什么类型的形式。E、 g
但这样看起来很快就会变得一团糟。在
相关问题 更多 >
编程相关推荐