WTForms日期验证 [英] WTForms date validation

查看:241
本文介绍了WTForms日期验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用Flask构建一个简单的Web应用程序.与此同时,我也使用了WTForms,但是我在从表单获取日期信息并对其进行验证时遇到了问题.

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 form and getting it validated.

这是表格:

from flask_wtf import FlaskForm
from wtforms import SubmitField
from wtforms.fields.html5 import DateField
from wtforms.validators import DataRequired
from datetime import date

class LeasForm(FlaskForm):
    start_date = DateField("Start date", default=date.today(), format='%d/%m/%Y', validators=[DataRequired(message="You need to enter the start date")],)
    end_date = DateField("End date", validators=[DataRequired(message="You need to enter the end date.")], format='%d/%m/%Y')
    submit = SubmitField("To payment")

然后在路线中,我有以下内容:

Then in routes i have the following:

@app.route('/url/<int:some_id>', methods=['GET', 'POST'])
def some_route(some_id):
....
    form = LeasForm()
    print("Request form: {}".format(request.form))
    print("Start date data: {}".format(form.start_date.data))
    print("End date data: {}".format(form.end_date.data))
    print("Leas form: {}".format(form.validate()))
    print("Leas form errors: {}".format(form.errors))
    if form.validate():
        return redirect(url_for('another_url'))
....

并在视图中:

....
<form action="" method="post">
    <div>{{form.errors}}</div>
    {{ form.hidden_tag() }}
    {{ form.start_date.title}}
    {{ form.start_date}}
    {{ form.end_date.title}}
    {{ form.end_date}}
    {{ form.submit}}
</form>

但是问题来了,当表单被提交时,我尝试获取数据,但事实却并非如此.这是从路由中的打印语句给出的输出:

but here comes the problem, when the form is submitted and i try to get the data it says it is none. This is the output that is given from the print statements in route:

Request form: ImmutableMultiDict([('csrf_token', 'CHANGED_TOKEN'), ('start_date', '2018-04-04'), ('end_date', '2018-04-06'), ('submit', 'To payment')])
Start date data: None
End date data: None
Leas form: False
Leas form errors: {'start_date': ['You need to enter the start date'], 'end_date': ['You need to enter the end date.']}

我已经尝试在WTForms文档和google中都找到了答案,但没有结果.

I have tried to find the answer in both the WTForms docs and using google with no result.

在此先感谢您,如果需要更多信息,请发送邮件或发表评论.

Thanks in advance and just send a message or comment if more information is needed.

推荐答案

WTForm自定义日期验证比较两个日期开始日期和结束日期 日期[开始日期不应大于结束日期 错误].

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

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

DateExample.html

<html>
<body>
<h1> Flask WFForm </h1>

{% if error %}
<p><strong> Error: </strong></p> {{error}}
{% endif %}

<form method="POST" action="{{url_for('index')}}">
  {{ form.csrf_token }}
{{ form.startdate.label }}
   {{ form.startdate }}
{{ form.enddate.label }}
   {{ form.enddate }}
<input type="submit" value="Submit">
</form>
</body>
</html>

这篇关于WTForms日期验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆