31

Currently in WTForms to access errors you have to loop through field errors like so:

for error in form.username.errors:
        print error

Since I'm building a rest application which uses no form views, I'm forced to check through all form fields in order to find where the error lies.

Is there a way I could do something like:

for fieldName, errorMessage in form.errors:
        ...do something
4

4 回答 4

44

实际form对象有一个errors属性,该属性包含字典中的字段名称及其错误。所以你可以这样做:

for fieldName, errorMessages in form.errors.items():
    for err in errorMessages:
        # do something with your errorMessages for fieldName
于 2011-06-24T17:01:32.037 回答
34

Flask 模板的更简洁的解决方案:

蟒蛇 3:

{% for field, errors in form.errors.items() %}
<div class="alert alert-error">
    {{ form[field].label }}: {{ ', '.join(errors) }}
</div>
{% endfor %}

蟒蛇2:

{% for field, errors in form.errors.iteritems() %}
<div class="alert alert-error">
    {{ form[field].label }}: {{ ', '.join(errors) }}
</div>
{% endfor %}
于 2013-12-17T20:58:08.037 回答
22

对于希望在 Flask 模板中执行此操作的任何人:

{% for field in form.errors %}
{% for error in form.errors[field] %}
    <div class="alert alert-error">
        <strong>Error!</strong> {{error}}
    </div>
{% endfor %}
{% endfor %}
于 2013-02-20T20:44:42.223 回答
2

ModelFormFieldsinSqlAlchemy一起使用时WTForms,如果您在对象内有嵌套对象(外键关系),则以下是正确显示字段相关错误的方法。

蟒蛇方面:

def flash_errors(form):
    for field, errors in form.errors.items():
        if type(form[field]) == ModelFormField:
            for error, lines in errors.iteritems():
                description = "\n".join(lines)
                flash(u"Error in the %s field - %s" % (
                    #getattr(form, field).label.text + " " + error,
                    form[field][error].label.text,
                    description
                ))
        else:
            for error, lines in errors.iteritems():
                description = "\n".join(lines)
                flash(u"Error in the %s field - %s" % (
                    #getattr(form, field).label.text + " " + error,
                    form[field].label.text,
                    description
                ))

神社方面:

  {% with messages = get_flashed_messages(with_categories=true) %}
    {% for message in messages %}
      {% if "Error" not in message[1]: %}
        <div class="alert alert-info">
          <strong>Success! </strong> {{ message[1] }}
        </div>
      {% endif %}

      {% if "Error" in message[1]: %}
        <div class="alert alert-warning">
         {{ message[1] }}
        </div>
      {% endif %}
    {% endfor %}
  {% endwith %}

希望有帮助。

于 2018-09-06T20:55:23.187 回答