wtforms隐藏字段值

时间:2012-11-29 05:40:49

标签: python wtforms

我正在使用WTForms,我遇到隐藏字段没有返回值的问题,而文档说它们应该。这是一个简单的例子:

forms.py:

from wtforms import (Form, TextField, HiddenField)

class TestForm(Form):
    fld1 = HiddenField("Field 1")
    fld2 = TextField("Field 2")

experiment.html:

{% from "_formshelper.html" import render_field %}
<html>
    <body>
        <table>
        <form method=post action="/exp">
            {% for field in form %}
                {{ render_field(field) }}
            {% endfor %}
            <input type=submit value="Post">
        </form>
        </table>        
    </body>
</html>

(render_field只是将标签,字段和错误放在td标签中)

experiment.py:

from flask import Flask, request, render_template

from templates.forms import *
from introspection import *

app = Flask(\__name__)                  
app.config.from_object(\__name__)
db_session = loadSession()

@app.route('/exp', methods=['POST', 'GET'])
def terms():
    mydata = db_session.query(Peter).one()
    form = TestForm(request.form, mydata)
    if request.method == 'POST' and form.validate():
        return str(form.data)
    return render_template('experiment.html', form = form)

if __name__ == '__main__':
    app.run(debug = True)  

mydata返回包含2个字段fld1和fld2的表中的唯一行。 fld1是整数自动增量字段。表单中填充了该数据,因此,如果我运行experiment.py,当我提交表单时,我会得到:

{'fld2':u'blah blah blah','fld1':u'1'}

但是如果我将fld1更改为HiddenField,当我点击提交时,我得到: {'fld2':u'blah blah blah','fld1':你'}}

我做错了什么?

1 个答案:

答案 0 :(得分:10)

我怀疑你的隐藏字段是(1)没有得到值集,或者(2)render_field宏没有正确构建它。如果我不得不打赌,我会说你的&#34; mydata&#34;对象没有您期望的值。

我将你的代码剥离到最低限度,这对我有用。注意我明确地给两个字段赋值:

from flask import Flask, render_template, request
from wtforms import Form, TextField, HiddenField

app = Flask(__name__)

class TestForm(Form):
  fld1 = HiddenField("Field 1")
  fld2 = TextField("Field 2")


@app.route('/', methods=["POST", "GET"])
def index():
  form = TestForm(request.values, fld1="foo", fld2="bar")
  if request.method == 'POST' and form.validate():
    return str(form.data)

  return render_template('experiment.html', form = form)

if __name__ == '__main__':
  app.run()

<html>
<body>
<table>
    <form method=post action="/exp">
        {% for field in form %}
            {{field}}
        {% endfor %}
        <input type=submit value="Post">
    </form>
</table>
</body>
</html>

这给了我{&#39; fld2&#39;:&#39; bar&#39;,&#39; fld1&#39;:&#39; foo&#39;}正如我所料。

检查mydata是否有属性&#34; fld1&#34;它有一个价值。我可能会明确地将它设置为form = TestForm(request.values,obj = mydata) - 它看起来并不像WTForms所关心的那样,但我有时会因为奇怪的挑剔而被烧毁。

如果这对您不起作用,请返回并发布您的HTML以及mydata的值。