wtforms hidden field value

后端 未结 1 1511
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 05:18

I am using WTForms, and I have a problem with hidden fields not returning values, whereas the docs say they should. Here\'s a simple example:

forms.py:

相关标签:
1条回答
  • 2020-12-31 06:00

    I suspect your hidden field is either (1) not getting a value set, or (2) the render_field macro isn't building it correctly. If I had to bet, I'd say your "mydata" object doesn't have the values you expect.

    I stripped your code down to the bare minimum, and this works for me. Note I am explicitly giving a value to both fields:

    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()
    

    and

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

    This gives me {'fld2': u'bar', 'fld1': u'foo'} as I would expect.

    Check that mydata has an attribute "fld1" and it has a value. I might set it explicitly like form = TestForm(request.values, obj=mydata) - it doesn't look like WTForms would care, but I've gotten burned by it being weirdly picky sometimes.

    If that doesn't work for you, come back and post your HTML and what values mydata has.

    0 讨论(0)
提交回复
热议问题