如何使Flask-WTF验证替代正确执行 [英] How to make Flask-WTF Validate Override execute properly

查看:134
本文介绍了如何使Flask-WTF验证替代正确执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的表单,其中包含一个URLFieldStringField.如下图所示:

I have created a simple form which contains a URLField and StringField. As shown below:

from flask_wtf import Form
from wtforms.fields import StringField
from wtforms.fields.html5 import URLField
#from flask.ext.wtf.html5 import URLField
from wtforms.validators import DataRequired, url

class BookmarkForm(Form):
    url = URLField('url')
    description = StringField('description')

    # override validate method of Form class for custom validation

    def validate(self):
        #app.logger.debug('Inside validate')
        if not self.url.data.startswith("http://") or\
            self.url.data.startswith("https://"):
            self.url.data = "http://" + self.url.data

        if not Form.validate(self):
            return False

        if not self.description:
            self.description.data = self.url.data

        return True

这是它在视图中的处理方式

@app.route('/add', methods = ['GET', 'POST'])
def add():
    #form = BookmarkForm(request.form)
    form = BookmarkForm()
    #if request.method == 'POST' and form.validate():
    if form.validate_on_submit():
        url = form.url.data
        description = form.description.data

        bm = models.Bookmark(url=url, description=description) # push to table
        db.session.add(bm)
        db.session.commit()

        # store_bookmarks(url,description) # old method

        flash("Stored '{}' '{}' ".format(url,description))
        return redirect(url_for('index'))
    return render_template('add.html', form=form)

但是,是什么导致验证覆盖无法执行?

推荐答案

我遇到了相同/相似的问题,在此代码中,只有第一个条件可以被忽略

I faced the same/similar issue where only the first conditio would be evaulated in this code

if not self.url.data.startswith("http://") or\
        self.url.data.startswith("https://"):
        self.url.data = "http://" + self.url.data

您需要为OR逻辑添加():

You need add () for the OR logic:

    if not (self.url.data.startswith("http://") or\
        self.url.data.startswith("https://")):
        self.url.data = "http://" + self.url.data

这篇关于如何使Flask-WTF验证替代正确执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆