Flask Ajax发布返回TypeError:“ NoneType”对象不可用于表单数据

时间:2019-01-04 00:45:20

标签: ajax forms flask csrf flask-wtforms

我已经看到有关如何使用wtf-forms在flask中实现ajax post方法的多个问题,并且已经阅读了文档。我以this post为例,但收到TypeError:'NoneType'对象不可迭代。我已经验证了表单数据未使用Ajax,并且一切正常。我不确定为什么它不适用于ajax请求。

我的表格:

class PathsForm(FlaskForm):
    name = StringField('Name', validators = [DataRequired()])
    paths = SelectField('Path')
    cbt_id = HiddenField('CBT ID', validators = [DataRequired()])

我的模板:

{% extends "base.html" %}

{% block content %}
    <h1>Edit {{ cbt.name }} </h1>
    <form action="" method="post">
        {{ form.hidden_tag() }}
    <table>
        <tr>
            <th>{{ form.name.label }}</th>
            <th>{{ form.paths.label }}</th>
        <tr>
            <td>{{ form.name(size=32) }}</td>
            <td>{{ form.paths() }}</td>
        </tr>
    </table>
    {{ form.cbt_id() }}
    <input type = "submit" value = "Add Path"/>
    </form>

    <script type="text/javascript">

    $(document).ready(function() {
        $('form').submit(function (e) {
            var url = "{{ url_for('process_cbt') }}"; // send the form data here.
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: $('form').serialize(),// serializes the form's elements.
                success: function (data) {
                    console.log(data)  // display the returned data in the console.
                }
            });
            e.preventDefault(); // block the traditional submission of the form.
        });
        // Inject our CSRF token into our AJAX request.
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ form.csrf_token._value() }}")
                }
            }
        })
    });
    </script>
{% endblock %}

我的烧瓶路线:

@app.route('/process_cbt', methods = ['POST'])
@login_required
def process_cbt():
    form = PathsForm()
    if form.validate_on_submit():
        return jsonify(data={'message':'Success'})
    return jsonify(data={'message': 'Failure'})

csrf令牌似乎已正确实施,我已按照the documentation设置了CSRF保护。

谁能告诉我为什么我会收到一个空表格?

谢谢

2 个答案:

答案 0 :(得分:0)

我相信您需要像这样将标头放入包含CSRF令牌的AJAX请求中

                      headers: {

                        "X-CSRFToken": "{{csrf_token()}}"
                      }

答案 1 :(得分:0)

经过比我想承认的更多的谷歌搜索,我看到了this answer并意识到我的问题不是基于ajax的,而是表单验证的问题。我动态地输入了自己的选择,因此当它尝试进行验证时,没有任何选择可以进行验证。我将视图更改为以下内容,一切都解决了。

def process_cbt():
    form = PathsForm()
    choice = request.form.get('paths')
    form.paths.choices = [(choice,choice)]
    if form.validate_on_submit():
        return jsonify(data={'message':'success'})
    return jsonify(data={'message': 'Failure'})