How to make Flask-WTF Validate Override execute properly

随声附和 提交于 2020-02-08 03:29:09

问题


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?

来源:https://stackoverflow.com/questions/32076750/how-to-make-flask-wtf-validate-override-execute-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!