wtforms不会将form.validate()返回为true

时间:2019-03-25 04:56:26

标签: flask flask-wtforms

我试图在Lalith Polepeddi's tutorial之后松散地验证联系表单的输入。我之前曾对本教程进行过细微的调整,但这次无论我如何尝试,输入内容都不会生效。

如果route.py中的form.validate()始终返回false。我将(整个venv仅上传了有问题的代码)https://github.com/1988mazdab2000/wtfwtf.git

forms.py文件:


class ContactForm(Form):
  name = TextField("Name",  [validators.Required("Please enter your name.")])
  email = TextField("Email",  [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")])
  subject = TextField("Subject",  [validators.Required("Please enter a subject.")])
  message = TextAreaField("Message",  [validators.Required("Please enter a message.")])
submit = SubmitField("Send")

我的route.py文件:

from flask import render_template, request, flash
from forms import ContactForm
from flask_mail import Message, Mail

mail = Mail()

@app.route('/')
def home():
  return render_template('home.html')

@app.route('/about')
def about():
  return render_template('about.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
  form = ContactForm()

  if request.method == 'POST':
    if form.validate() == False:
      flash('All fields are required.')
      return render_template('contact.html', form=form)
    else:
      msg = Message(form.subject.data, sender='contact@example.com', recipients=['your_email@example.com'])
      msg.body = """
      From: %s <%s>
      %s
      """ % (form.name.data, form.email.data, form.message.data)
      mail.send(msg)

      return render_template('contact.html', success=True)

  elif request.method == 'GET':
return render_template('contact.html', form=form)

任何帮助,将不胜感激。在过去的三个月中,我使用了相同的代码来执行此操作,但我陷入了困境。

我尝试使用不同的验证器,并在两个不同的Pi上重新安装了raspbian。

我希望表单验证器能够正常工作。

2 个答案:

答案 0 :(得分:0)

在模板中,使用 {{ form.hidden_tag() }} 进行csrf保护。

<form action="{{ url_for('contact') }}" method="post">

      {{ form.hidden_tag() }}
</form>

答案 1 :(得分:0)

正如@VillageMonkey所说,请使用validate_on_submit。可以在official documentation中找到更多信息。

以下是使用Flask-WTF使用表单验证的示例。在此示例中,登录表单需要有效的电子邮件地址和密码,密码长度至少为6个字符,最多为35个字符。

app.py

from flask import render_template, url_for, request, redirect, flash, Flask
from forms import LoginForm

app = Flask(__name__)
app.secret_key = 'secret key'

@app.route("/login", methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if request.method == 'POST':
        if form.validate_on_submit() == False:
          flash('Form validation failed')          
          return render_template('login.html', form=form)
        user_email = form.email.data
        user_password = form.password.data
        if user_email and user_password:
            return "{} - {}".format(user_email, user_password)
    return render_template('login.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo

class LoginForm(FlaskForm):
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=35)])
    submit = SubmitField('Login')

login.html

<!DOCTYPE html>
<html>
<head>
  <title>Login</title>
</head>
<body>
  {% with messages = get_flashed_messages() %}
  {% if messages %}
  <ul class=flashes>
    {% for message in messages %}
    <li>{{ message }}</li>
    {% endfor %}
  </ul>
  {% endif %}
  {% endwith %}
  <form method="POST" action="">
    {{ form.csrf_token }}
    <div>
      {{ form.email.label }} {{ form.email }}
      {% if form.email.errors %}
      <ul style="color: red;">
        {% for error in form.email.errors %}
        <li>{{ error }}</li>
        {% endfor %}
      </ul>
      {% endif %}
    </div>
    <div>
      {{ form.password.label }} {{ form.password }}
      {% if form.password.errors %}
      <ul style="color: red;">
        {% for error in form.password.errors %}
        <li>{{ error }}</li>
        {% endfor %}
      </ul>
      {% endif %}
    </div>
    <div>
      {{ form.submit }}
    </div>
  </form>

</body>
</html>

目录结构:

.
├── app.py
├── forms.py
└── templates
    └── login.html

requirements.txt

Click==7.0
Flask==1.0.2
Flask-WTF==0.14.2
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.1
Werkzeug==0.15.0
WTForms==2.2.1

输出:

获取login路线的请求:

login form

发布login路线的请求(验证失败):

failed validation

发布login路线的请求(成功验证后):

validated response