Flask: form.validate_on_submit() 抛出类型错误

Flask: form.validate_on_submit() throwing type error

每次我在“/signup”视图中提交表单时,views.py 中的 form.validate_on_submit() 都会抛出以下错误:

TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

堆栈跟踪很长,我没有立即看到任何明显的东西。我不知道为什么要这样做。我按照 Flask-WTF docs 验证表单。

编辑:Here 是我看到的堆栈跟踪。

views.py

from myapp import app
from flask import render_template, redirect
from forms import RegistrationForm

@app.route('/', methods=['POST', 'GET'])
@app.route('/signup', methods=['POST', 'GET'])
def signup():
    form = RegistrationForm()
    if form.validate_on_submit():
        # Redirect to Dash Board
        return redirect('/dashboard')
    return render_template("signup.html", form=form)

@app.route('/login')
def login():
    return "<h1>Login</h1>"

@app.route('/dashboard')
def dashboard():
    return "<h1>Dashboard</h1>"

forms.py

from flask_wtf import FlaskForm
from wtforms import TextField, PasswordField
from wtforms.validators import InputRequired, Email, Length

class RegistrationForm(FlaskForm):
    username = TextField('username', validators=[InputRequired(), Length(min=4, max=30)])
    email = TextField('email', validators=[InputRequired(), Email, Length(max=25)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])

class LoginForm(FlaskForm):
    username = TextField('username', validators=[InputRequired(), Length(min=4, max=30)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])

signup.html

{% extends "base.html" %}
{% block content %}
<h1>Sign Up</h1>

<form method="POST" action="/signup">
{{ form.hidden_tag() }}
<p>Username:</p>
{{ form.username() }}
<p>Email:</p>
{{ form.email() }}
<p>Password:</p>
{{ form.password() }}
<br/>
<br/>
<button type="Submit" value="submit" name="submit">Submit</button>
</form>
{% endblock %}

我想通了!在 forms.py 中,我的 RegistrationFormemail 属性应该是:

email = TextField('email', validators=[InputRequired(), Email(), Length(max=25)])

我忘记了 Email 参数的括号。