WTForms form with custom validate method is never valid

谁说我不能喝 提交于 2020-07-09 02:36:13

问题


I want to get the data for a user input date, or the current date if nothing is entered. I used WTForms to create a form with a date input, and override validate to return True if the date field has data. However, the form is always invalid even if I enter a date. Why isn't this working?

class ChooseDate(Form):
    date = DateField(format='%m-%d-%Y')

    def validate(self):
        if self.date.data is None:
            return False
        else:
            return True

@app.route('/index', methods=['GET', 'POST'])
def index():
    date_option = ChooseDate()
    print(date_option.date.data)  # always None

    if date_option.validate():
        request_date = date_option.date.data
    else:
        request_date = datetime.today().date()

    return render_template_string(template_string, form=date_option, date=request_date)

回答1:


You aren't overriding validate correctly. validate is what triggers the form to read the data and populate the data attributes of the fields. You're not calling super, so this never happens.

def validate(self):
    res = super(ChooseDate, self).validate()
    # do other validation, return final res

In this case there's no reason to override validate, you're just trying to make sure data is entered for that field, so use the built-in InputRequired validator. Using field validators will add error messages to the form as well.

from wtforms.validators import InputRequired

date = DateField(validators=[InputRequired()])

See the docs for more on validation.

Finally, you need to pass the form data to the form. If you were using the Flask-WTF extension's FlaskForm, this would be passed automatically.

from flask import request

form = ChooseDate(request.form)


来源:https://stackoverflow.com/questions/35778199/wtforms-form-with-custom-validate-method-is-never-valid

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