WTForms date validation

后端 未结 1 520
误落风尘
误落风尘 2021-01-16 05:53

I am currently trying to build a simple web application using Flask. With this i am also using WTForms, however i am having problem with getting date information from the fo

1条回答
  •  攒了一身酷
    2021-01-16 06:36

    WTForm custom date validation compare two dates Start date and End date [Start date should not be greater than end date if so give error].

    DateExample.py

        from flask import Flask, render_template
        from flask_wtf import FlaskForm
        from datetime import date
        from wtforms.fields.html5 import DateField
        from wtforms.fields.html5 import DateTimeField
    
        app = Flask(__name__)
        app.config['SECRET_KEY']='secretkey'
    
        class TestForm(FlaskForm):
            startdate = DateField('Start Date',default=date.today)
            enddate = DateField('End Date',default=date.today)
    
            def validate_on_submit(self):
                result = super(TestForm, self).validate()
                if (self.startdate.data>self.enddate.data):
                    return False
                else:
                    return result
    
        @app.route('/dateExample',methods=['GET','POST'])
        def index():
            error = None
            form = TestForm()
            if form.validate_on_submit():
                return 'Start Date is : {} End Date is : {}'.format(form.startdate.data, form.enddate.data)
            else:
                error = "Start date is greater than End date"
            return render_template('dateExample.html',form=form,error = error)
    
        if __name__ =="__main__":
            app.run(debug=True,port=5000)
    

    DateExample.html

    
    
    

    Flask WFForm

    {% if error %}

    Error:

    {{error}} {% endif %}
    {{ form.csrf_token }} {{ form.startdate.label }} {{ form.startdate }} {{ form.enddate.label }} {{ form.enddate }}

    0 讨论(0)
提交回复
热议问题