WTForms getting the errors

前端 未结 4 1301
一个人的身影
一个人的身影 2020-12-09 03:34

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

for error in form.username.errors:
        print error

相关标签:
4条回答
  • 2020-12-09 04:00

    A cleaner solution for Flask templates:

    Python 3:

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

    Python 2:

    {% for field, errors in form.errors.iteritems() %}
    <div class="alert alert-error">
        {{ form[field].label }}: {{ ', '.join(errors) }}
    </div>
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-09 04:02

    With ModelFormFields in SqlAlchemy when used with WTForms, if you have a nested object inside an object (foreign key relationships), here is how you show the relevant errors for fields properly.

    Python side:

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

    Jinja side:

      {% 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 %}
    

    Hope that helps.

    0 讨论(0)
  • 2020-12-09 04:13

    For anyone looking to do this in Flask templates:

    {% for field in form.errors %}
    {% for error in form.errors[field] %}
        <div class="alert alert-error">
            <strong>Error!</strong> {{error}}
        </div>
    {% endfor %}
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-09 04:16

    The actual form object has an errors attribute that contains the field names and their errors in a dictionary. So you could do:

    for fieldName, errorMessages in form.errors.items():
        for err in errorMessages:
            # do something with your errorMessages for fieldName
    
    0 讨论(0)
提交回复
热议问题