如何使Flask-WTF验证覆盖正确执行

时间:2015-08-18 15:36:10

标签: python flask flask-wtforms

我创建了一个包含URLFieldStringField的简单表单。如下图所示:

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)

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

1 个答案:

答案 0 :(得分:0)

我遇到了相同/相似的问题,在此代码中仅会评估第一个条件

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

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

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