Flask隐藏输入未在模板

时间:2016-12-05 20:59:51

标签: python html flask

所以我试图将Jinja2模板中的值传递回我的Python代码。我试图用隐藏的输入来做这件事。我的表格类是:

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

我的表格是这样的:

<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是我在渲染模板时传递的字符串。

但是,在检查form.hidden.data的值时,它会以''的形式返回。该标记也会呈现为<input id="hidden" name="hidden" type="hidden" value="">

我也尝试过value={{ result }}代替value="{{result}}",但这会让Jinja抛出TemplateSyntaxError。

关于如何做到这一点的任何想法?

修改 每次调用函数时我都会覆盖result。 这是我的路线功能:

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

3 个答案:

答案 0 :(得分:2)

{{ form.hidden(value="{{ result }}") }}已使用外部双花括号进行模板化语法。因此,您应该能够清楚地写出结果变量,如下所示:{{ form.hidden(value=result) }}

编辑

{{ form.hidden_tag() }}替换为{{ form.csrf_token() }}以及执行原始答案中的内容 您可能还必须使用form = forms.TrueOrFalseForm(request.form)实例化表单。如果你不这样做,有些形式表现得很奇怪。

答案 1 :(得分:0)

由于您在模板中使用{{ form.hidden_tag() }},因此无需显式呈现hidden表单字段。它将包含在hidden_tag()电话中。

您可以在渲染模板之前在视图中设置隐藏字段的值。

<强> views.py

form.hidden.data = result

return render_template("index.html",form=form)

<强>的index.html

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

答案 2 :(得分:0)

我的建议是:

import random
print("1. Encrypt")
print("2. Decrypt")
print(" ")

selection = int(input("What would you like to do? [1,2]? "))

while selection == 1:
    plainText = input('Enter the message you wish to encrypt: ')

    # right now the program encrypts the string at random between 1 and 95.  
    # All of the printable ASCII characters.
    # the code below is written for when I can take the parameters of 1-95
    # off and any input will simply loop around.
    distance = random.randint(1, 95)
    if distance < 1 or distance > 95:
        print('Try Again')
        continue
    else:

        # saves the random integer or (key) 
        # directly to a file without the user seeing it.

        f = open('..\\Desktop\\encryptPractice\\theKey.txt', 'w+')

        for key in range(1):
            number = distance
            f.write(str(number))

        f.close()

        code = ""

        for ch in plainText:
            ordvalue = ord(ch)
            ordvalue = ordvalue + distance

            while ordvalue < 32:
                ordvalue += 95
            while ordvalue > 126:
                ordvalue -= 95

            code += chr(ordvalue)

            # saves the encrypted message 
            # directly to a file without the user seeing it.

        f = open('..\\Desktop\\encryptPractice\\theMessage.txt', 'w+')

        for theMessage in range(1):
            secret = code
            f.write(str(secret))
        f.close()

        print('Your message has been saved to the file named theMessage.txt')
        break


# This is the decryption block - OPTION 
# 2.)*********************************************

while selection == 2:

    """
    I want to simply be able to open the file with the 'encrypted'
    message on it and then open the file with the 'key' on it and
    have the program decrypt the message and save it back to the
    same file.

    Both of the solutions below cause the program to read the
    'encrypted' message over and over and over and...you get it.
    """

    f = open('..Desktop\\encryptPractice\\theMessage.txt','r')
    for line in f:
        print(line)


    f = open('..Desktop\\encryptPractice\\theMessage.txt','r')
    while True:
        line = f.readline()
        if line == ""
            break
        print(line)

先前的答案是正确的,但我认为他们需要进行一些更正,将 safe 放入变量jinja:

hidden field set values