Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a value for a hidden field in a Flask form, using wtf.quick_form?

I'm struggling to find out how to pass values to a hidden field in a flask-wft quick form

The template to display the form is

{% block content %}
    <div class="row">
        <div class="col-md-4">
            {{ wtf.quick_form(form) }}
        </div>
    </div>
{% endblock %}

I am defining the form like this

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField
from wtforms import HiddenField
from wtforms.validators import DataRequired, Length


class MyForm(FlaskForm):
    myhidden = HiddenField()
    textblock = TextAreaField('textblock', validators=[Length(min=0, max=2000)])
    submit = SubmitField('Submit')

And rendering it like this

form = MyForm()
... 
return render_template('form.html', title='my form', form=form)

I tried to give a value to

form.myhidden = "test value"

But the rendered page shows the field value as empty

Is it possible to use hidden fields in wtf.quick_form at all?

like image 658
576i Avatar asked Jun 25 '18 15:06

576i


People also ask

What does {{ form Hidden_tag () }} do?

The form. hidden_tag() template argument generates a hidden field that includes a token that is used to protect the form against CSRF attacks. All you need to do to have the form protected is include this hidden field and have the SECRET_KEY variable defined in the Flask configuration.

What is WTForms in Flask?

WTForms is a Python library that provides flexible web form rendering. You can use it to render text fields, text areas, password fields, radio buttons, and others. WTForms also provides powerful data validation using different validators, which validate that the data the user submits meets certain criteria you define.

What is form Validate_on_submit?

The validate_on_submit() method of the form returns True when the form was submitted and the data was accepted by all the field validators. In all other cases, validate_on_submit() returns False . The return value of this method effectively serves to determine whether the form needs to be rendered or processed.


1 Answers

That was too easy.

form = MyForm(myhidden = 'test value')

will set the value for the field.

like image 130
576i Avatar answered Sep 21 '22 09:09

576i