Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask hidden input doesn't get set in template

Tags:

python

html

flask

So I'm trying to pass a value from a Jinja2 template back to my Python code. I'm trying to do this with a hidden input. My form class is this:

class TrueOrFalseForm(flask_wtf.FlaskForm):
    choice = RadioField(choices=[('True', 'TRUE'), ('False', 'FALSE')], validators=[validators.InputRequired()])
    hidden = HiddenField()
    submit = SubmitField('Submit')

And my form is this:

<form autocomplete="off" action="" method="post">
    {{ form.hidden_tag() }}
    <div style="text-align: center">
        <div style="display: inline-block">
            {{ form.choice }}
            {{ form.hidden(value="{{ result }}") }}
            {{ form.submit(class_="btn btn-primary btn-lg") }}
        </div>
    </div>
</form>

result is a string that I'm passing when rendering the template.

When checking the value of form.hidden.data, though, it comes back as ''. The tag also renders as <input id="hidden" name="hidden" type="hidden" value="">.

I've also tried doing value={{ result }} instead of value="{{result}}" but that makes Jinja throw a TemplateSyntaxError.

Any idea on how to do this?

EDIT: I'm overwriting result every time I call the function. This is my route function:

@app.route('/', methods=['GET', 'POST'])
def home():
    form = forms.TrueOrFalseForm()
    x = random.randint(-100, 100)
    y = random.randint(-100, 100)
    statement_str = generate_statement_string(2)
    tree = BinTree.build_tree(statement_str)
    statement_result = BinTree.solve_tree(tree, x, y) # result gets overwritten here
    if form.validate_on_submit():
        if not flask_login.current_user.is_anonymous:
            # same as the else, except with some sql, not relevant
        else:
            if form.choice.data == form.hidden.data:
                flask.flash('Correct!')
            else:
                flask.flash('Incorrect!')
    return flask.render_template('home.html', x_value=str(x), y_value=str(y), statement=statement_str,
                             result=str(statement_result), form=form)
like image 912
Barak Nehmad Avatar asked Nov 24 '25 16:11

Barak Nehmad


1 Answers

{{ form.hidden(value="{{ result }}") }} is already in templating syntax with the outer double curly brackets. Therefore, you should just be able to plainly write the result variable, like this: {{ form.hidden(value=result) }}

EDIT

Replace {{ form.hidden_tag() }} with {{ form.csrf_token() }} as well as doing what is in my original answer.
You may also have to instantiate the form with form = forms.TrueOrFalseForm(request.form). Some forms behave weirdly if you don't do that.

like image 99
Taehan Stott Avatar answered Nov 26 '25 04:11

Taehan Stott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!