【问题标题】:Flask WTForms Validate on Submit not workingFlask WTForms Validate on Submit 不工作
【发布时间】:2021-02-05 00:44:48
【问题描述】:

我正在我的应用程序中的一个页面上工作,其中用户使用 WTForms 在评论页面上提交评论,并且在单击提交按钮时,应该显示文本“成功”。目前没有发生这种情况,因为单击提交后,评论页面会自动重新加载,但出现错误。 我已经创建了其他需要表单验证的页面,除了这个页面之外,我似乎无法弄清楚为什么,尽管从其他页面复制了代码。 非常感谢任何见解!

错误图片截图

这是我的 HTML 代码

<html>
    <body>
        {% for books in books %}
        {{books.title}} 
        {% endfor %}

<form action = "{{ url_for('review', isbn=books.isbn)}}", method = "POST">
    <div>
    <br>{{ form.review(class_='form-control',placeholder ='Leave a review here')}}</br>
    <ul>
    {% for error in form.review.errors %}
        <li>{{ error }}</li>
    {% endfor %}
    </ul>
    <br>{{ form.rating(class_='form-control',placeholder ='Leave a rating here')}}</br>
    <ul>
    {% for error in form.rating.errors %}
        <li>{{ error }}</li>
    {% endfor %}
    </ul>
    {{form.csrf_token}}  
    {{form.submit_button }}
  
</div>

</form>

    </body>
    </html>

Python 代码

@app.route("/review/<string:isbn>", methods = ['GET', 'POST'])
@login_required 
def review(isbn):
     review = Books.query.filter_by(isbn=isbn).all()
     review_form = ReviewForm()
     if review_form.validate_on_submit():
           return "Success"
     
     return render_template("review.html", books = review, form = review_form)

WTForms 字段

class ReviewForm(FlaskForm):
     """ Review """
     review = StringField('review_label', widget=TextArea(), validators = [InputRequired(message = "Review can't be empty")])
     rating = StringField('rating_label', validators= [InputRequired(message="Please input a rating")])
     submit_button = SubmitField('Submit')

【问题讨论】:

    标签: python html flask-wtforms wtforms


    【解决方案1】:

    我建议如下。让我知道这是否有帮助! :)

    from markupsafe import escape
    @app.route("/review/<string:isbn>", methods = ['GET', 'POST'])
    @login_required 
    def review(isbn):
         review = Books.query.filter_by(isbn=isbn).all()
         review_form = ReviewForm()
         if review_form.validate_on_submit():
               return "Success %s" % escape(isbn)
         
         return render_template("review.html", books = review, form = review_form)
    

    reference flask documentation

    【讨论】:

    • 感谢您的意见!不幸的是,它没有用。我认为问题在于 路线(尽管我自己不确定根本原因)。我尝试了两种暂时解决问题的方法 1)我从包含它的代码中的所有位置删除了路由和所有“isbn”实例,并且它有效 - 当我单击提交按钮时,分页显示“成功”。 2)我将用户重定向到不同的页面返回重定向(url_for('success'))。如果您或任何人对此问题有任何见解,请告诉我!
    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 2022-07-14
    • 2012-05-20
    • 1970-01-01
    • 2021-01-14
    • 2021-09-03
    • 2014-09-14
    相关资源
    最近更新 更多