如何从flask_wtforms获取验证错误

时间:2019-08-14 04:46:29

标签: flask flask-wtforms

我想从flask_wtforms的textarea表单中获取验证错误。我知道您可以通过将其包含在html中来获得它们:

{% for error in form.post.errors %}
    {{ error }}
{% endfor %}

但是这对我来说并不完全有效,因为Im使用引导程序模态并且Length验证要求您提交表单,刷新页面,这不同于DataRequired()验证程序阻止您提交。很难说表格失败了。

基本上,我想从python端获取错误并刷新它们。

我尝试使用form.post.errors访问错误,但是它不起作用,它总是返回一个空集。

这是我的索引代码

def index():
    form = PostForm()
    // I would like to get the errors via form.post.errors here and I don't understand why I can't
    if form.validate_on_submit():
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post is now live!', 'primary')
        return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('index', page=posts.next_num) if posts.has_next else None
    prev_url = url_for('index', page=posts.prev_num) if posts.has_prev else None
    return render_template('index.html', title='Home', posts=posts.items, form=form, next_url=next_url, prev_url=prev_url)
{% extends "base.html" %}

{% block content %}

    {% if form %}
    <div class="modal fade" id="submitPost" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <form action="" method="post">
                {{ form.hidden_tag() }}
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="submitPostLabel">Submit Post</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="PostText">{{ form.post.label }}</label>
                            {{ form.post(cols=32, rows=4, class="form-control") }}<br>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <!-- <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> -->
                        {{ form.submit(class="btn btn-primary") }}
                    </div>
                </div>
            </form>
        </div>
    </div>
    {% endif %}

上面的html文件基本上是

<form action="" method="post">
    {{ form.hidden_tag() }}
    {{ form.post.label }}
    {{ form.post(cols=32, rows=4, class="form-control") }}
    {{ form.submit(class="btn btn-primary") }}
</form> 

带有一些引导程序

1 个答案:

答案 0 :(得分:0)

您可以通过添加以下内容来打印错误:print form.errors.items()。

form.errors