python - 如何在 Flask 中传递 "WTF object"

标签 python flask flask-wtforms

我正在使用flask开发一个网站,现在遇到了一个问题。 我在想是否可以在 flask 中传递“WTF 形式”对象。 就像,

@app.route('/')
@app.route('/index')
@login_required
def index():
  user = flask.g.user
  form = PostForm()
  return flask.render_template("index.html",
        title="Home",
        user=user,
        form = form)

这个表单是PostForm的一个实例,实际上将由以下代码处理:

@app.route('/note/<int:id>', methods=['POST'])
def note(id):

form = ?(how to get this form?)?
if form.validate_on_submit():
   print id
   content = form.body.data
   currentTime = time.strftime('%Y-%m-%d', time.localtime(time.time()) )
   user_id = id
   return flask.redirect(flask.url_for('login'))

return flask.redirect( flask.request.args.get('next') or
        flask.url_for('index') )

在模板中,我将操作设置为“/note/1”,因此它将转发到该地址。但问题是,如何获得在函数 index 中创建的表单?

我尝试使用flask.g(显然,它不起作用,因为这是另一个请求)。我还尝试使用全局变量。它也失败了。

谁能给我一个解决方案或任何建议吗?

提前谢谢您!

最佳答案

您只需在 note 路由中构建新版本的 PostForm 并在 request.form 中使用发布的数据:

from flask import request

@app.route('/note/<int:id>', methods=['POST'])
def note(id):
    form = PostForm(request.form)
    # or, if you are using Flask-WTF
    # you can do
    # form = PostForm()
    # and Flask-WTF will automatically pull from request.form

关于python - 如何在 Flask 中传递 "WTF object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23898014/

相关文章:

Python-创建虚拟环境时没有pip

python - 如何在wxpython中改变wx.TextCtrl小部件的形状?

python - 将零添加到列表中

python - 类型错误 : <Response 36 bytes [200 OK]> is not JSON serializable

python-3.x - 如何使用 wtforms 制作 BooleanField 列表

python - Flask WTForms 表单未提交但未输出验证错误

python - lxml/MathML XML 架构 - 如何修复 "content model is not determinist."错误?

python - 确保 POST 数据是有效的 JSON

python - 如何将 Pandas 数据框显示到现有的 flask html 表中?

flask - Flask:从数据库内容动态填充表单