简体   繁体   中英

how to view WTForms validation errors?

I am writing some basic tests and have a test failing.

def test_new_user_registration(self):
  self.client.get('/user/register')
  form = RegistrationForm(
    email=u'crow@crow.com',
    first_name=u'Alex',
    last_name=u'Frazer',
    username=u'crow',
    password=u'fake_password',
    confirm_password=u'fake_password'
  )
  self.assertTrue(form.validate())

The assertion error is failing on form.validate() , but how can I view what the validation errors are?

Use form.errors :

errors

A dict containing a list of errors for each field. Empty if the form hasn't been validated, or there were no errors.

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

I had the same problem, and couldnt find the answer anywhere. This is a snippet from my index.html

 <div class="all">
      <div class="form-group">
        {{ form.phone.label(id="label1") }}
        {% if form.phone.errors %}
        {{ form.phone(class="form-control form-control-lg is-invalid") }}
        <div class="invalid-feedback">
            {% for error in form.phone.errors %}
                <span>{{ error }}</span>
            {% endfor %}
        </div>
    {% else %}
    {{ form.phone(class="form-control", placeholder="Enter Your Phone Number", )}}
    {% endif %}
       

      </div>
    </div>

And in my forms.py

class AddContestant(FlaskForm):
number = StringField('Phone number', validators=[DataRequired(), Length(min=10, max=15, message="Your phone number should be more than 10 digits and less than 15")])

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM