How to make Flask-WTF Validate Override execute pr

2019-08-30 03:30发布

问题:

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

This is how its handled in view

@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)

But, what is causing the validate override to not execute?