簡體   English   中英

Flask object 沒有屬性“validate_on_submit”

[英]Flask object has no attribute 'validate_on_submit'

我遇到了來自wtforms的 form.validate_on_submit() 方法的問題,每次提交表單時都會引發以下錯誤:

'LoginForm' object has no attribute 'validate_on_submit'

forms.py:

from wtforms import Form, validators, StringField, PasswordField

class LoginForm(Form):
    email = StringField('Email Address', [validators.DataRequired(message='Field required')])
    password = PasswordField('Password', [validators.DataRequired(message='Field required')])

路線.py

from flask import Flask, escape, request, render_template, redirect, url_for
from securepi import app, tools
from securepi.forms import LoginForm
@app.route('/login/', methods=['GET', 'POST'])
def login():
error = None
try:
    form = LoginForm(request.form)

    if request.method == "POST" and form.validate_on_submit():
        email = str(form.email.data)
        password = tools.encrypt(str(form.password.data))
        print("email:  {}, password: {}".format(email, password))


        # if valid account create session and redirect to index


        return redirect(url_for('index'))
    else:
        print("FAIL")
        error = "Invalid username or password"

except Exception as e:
    return(str(e))

return render_template('login.html', form = form)

和表格

<form action="" method="post">
  <div class="form-group has-feedback">
    <input type="email" name="email" class="form-control" placeholder="Email" value="{{ request.form.email }}">
    <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
  </div>
  <div class="form-group has-feedback">
    <input type="password" name="password" class="form-control" placeholder="Password" value="{{ request.form.password }}">
    <span class="glyphicon glyphicon-lock form-control-feedback"></span>
  </div>
  <div class="row">
    <!-- /.col -->
    <div class="col-xs-12">
      <button type="submit" class="btn btn-primary btn-block">Log in</button>
    </div>
    <!-- /.col -->
  </div>
</form>

您可以嘗試將 forms.py 更改為以下內容嗎?

from flask_wtf import FlaskForm
from wtforms import validators, StringField, PasswordField

class LoginForm(FlaskForm):
    email = StringField('Email Address', [validators.DataRequired(message='Field required')])
    password = PasswordField('Password', [validators.DataRequired(message='Field required')])

Forms class文檔說:

證實()

通過在每個字段上調用 validate 來驗證表單,將任何額外的 Form.validate_<fieldname> 驗證器傳遞給字段驗證器。

好像您正在嘗試驗證表單中缺少的on_submit字段。 簡單地使用validate()應該可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM