3

提交包含动态填充的 SelectField 的表单时出现问题。由于某种原因,当 Flask 尝试验证 CSRF 令牌时,当 SelectField 在表单中时它总是失败。当我从表单中删除 SelectField 时,它会成功验证 CSRF 令牌。

有没有人遇到过这种行为?

编辑

形式:

class AddToReportForm(Form):
    selectReportField = SelectField(u'Reports',choices=[('test1','test')])

    def __init__(self, *args, **kwargs):
        """
        Initiates a new user form object
        :param args: Python default
        :param kwargs: Python default
        """
        Form.__init__(self, *args, **kwargs)




    def validate(self,id_list):
        rv = Form.validate(self)

        if not rv:
            print False
            #Check for the CSRF Token, if it's not there abort.
            return False

        print True
        return True

Jinja2:

<form  method=post name="test">
{{ form.hidden_tag()}}




    {{ form.selectReportField }}
    <a href="#" onclick="$(this).closest('form').submit()" class="button save">Add to report</a>

</form>

渲染:

form = AddToReportForm()
return render_template('random',title='add reports',form=form
4

3 回答 3

3

你在哪里设置 SECRET_KEY?它必须在 Form 类中可用:

class AddToReportForm(Form):
    selectReportField = SelectField(u'Reports',choices=[('test1','test')])
    SECRET_KEY = "myverylongsecretkey"

    def __init__(self, *args, **kwargs):
        """
        Initiates a new user form object
        :param args: Python default
        :param kwargs: Python default
        """
        Form.__init__(self, *args, **kwargs)
    def validate(self,id_list):
        rv = Form.validate(self)

        if not rv:
            print False
            #Check for the CSRF Token, if it's not there abort.
            return False
        return True

或在应用程序引导程序中:

app = Flask(__name__)
app.secret_key = 'myverylongsecretkey'

或在构造函数中:

form = AddToReportForm(secret_key='myverylongsecretkey')
return render_template('random',title='add reports',form=form)
于 2013-05-29T13:31:30.570 回答
2

我仍然看不到 SelectField 和 CSRF 之间的任何联系。该validate方法有点可疑,额外的参数会触发以下测试用例,但就目前而言,这似乎工作得很好:

from flask import Flask, render_template_string
from flaskext.wtf import Form, SelectField

app = Flask(__name__)
app.debug = True
app.secret_key = 's3cr3t'


class AddToReportForm(Form):
    selectReportField = SelectField(u'Reports', choices=[('test1', 'test')])


@app.route('/test', methods=['GET', 'POST'])
def test():
    form = AddToReportForm()
    if form.validate_on_submit():
        print 'OK'
    return render_template_string('''\
<form method=post name="test">
{{ form.hidden_tag()}}
{{ form.selectReportField }}
<input type="submit">
</form>
''', form=form)


app.run(host='0.0.0.0')
于 2013-05-29T16:33:23.777 回答
0

推荐用途:

app.secret_key = 'key here' # key user defined
于 2017-02-10T03:58:08.790 回答