【发布时间】:2017-09-12 08:24:13
【问题描述】:
我在我的 Flask 应用程序中使用 flask_form 并且已经被“CSRF 令牌不匹配”卡住了几个小时。
<form method="post" action="{{ url_for('auth.login') }}" role="form">
{{ form.hidden_tag() }}
{{ wtf.form_errors(form, hiddens="only") }}
{{ wtf.form_field(form.email)}}
{{ wtf.form_field(form.password)}}
<p><button type="submit">Login</button></p>
</form>
views.py
@auth.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
print('login form received on server and is valid')
# check whether user exists in the database and whether
# the password entered matches the password in the database
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data) and check_password_hash(user.pwd, form.password.data):
# log employee in
login_user(user) #,remember=True)
# redirect to the home page after login
return redirect(url_for('grapher.upload'))
# when login details are incorrect
else:
flash('Invalid email or password.', 'info')
# load login template
return render_template('auth/login.html', form=form, title='Login')
表格
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email(), Length(min=1,max=254, message='The maximum length of this filed is 254 characters')])
password = PasswordField('Password', validators=[DataRequired(), Length(max=20, message='Password maximium length is 20 characters.')])
为什么会出现这个错误?
【问题讨论】:
-
请发布您的整个错误信息
-
请添加错误和初始化令牌的代码
-
我收到的唯一错误消息是我的表单下的“CSRF 令牌不匹配”。我怎样才能得到更相关的错误消息?我没有使用 CSRF 扩展,而只是 wtf_form (根据文档:“任何使用 FlaskForm 处理请求的视图都已经获得 CSRF 保护”)
-
@Nabin 有什么想法吗?
-
@EspoirMurhabazi,我遇到了同样的问题,我在模板中有
form.hidden_tag()。the code where you initialise the token是什么意思?我是否需要以某种方式显式初始化令牌?
标签: python flask flask-wtforms