在使用 Flask 与其模板引擎 Jinja2 结合 WTF forms(Flask-WTF)时,集成日期时间选择组件可以提高表单的用户体验。下面是一种方法来实现日期和时间选择功能:

Jinja与WTF form使用日期时间组件的解决方法_表单

1、问题背景

在使用 Jinja 和 WTF form 来创建表单时,遇到一个问题:希望在表单中添加日期时间组件,但使用 form.validate_on_submit() 时总是返回 False。 以下是表单代码:

class FoodForm(Form):
    food_name = StringField('Food Name', validators=[Required()])
    food_description = StringField('Food Description', validators=[Required()])
    price = FloatField('Price', validators=[Required()])
    event_starts = DateTimeField('Event Starts', validators=[Required()])
    event_ends = DateTimeField('Event Ends', validators=[Required()])
    food_types = ['Indian', 'American', 'Chinese', 'Italian', 'Other', 'French',
                  'Deli','Mediterranean', 'Japanese']
    food_choices = [(i+1, food_type) for i, food_type in enumerate(sorted(food_types))]
    cuisine_type = SelectField('Cuisine Type', choices=food_choices, validators=[Required()])
    submit = SubmitField('Submit')

Jinja 模板代码如下:

<form class="form form-horizontal" role="form" method="POST">
    {{ form.hidden_tag() }}
    <div class="row">
        <div class="col-md-6">{{ form.food_name.label }} </div>
        <div class="col-md-6">{{  form.food_name() }} {% for error in form.food_name.errors %} <div class="flash">{{ message }} </div>{% endfor %}</div>
    </div>
    <div class="row">
        <div class="col-md-6">{{ form.food_description.label }} </div>
        <div class="col-md-6">{{  form.food_description() }} {% for error in form.food_description.errors %} <div class="flash">{{ message }}</div>{% endfor %}</div>
    </div>
    <div class="row">
        <div class="col-md-6">{{ form.event_starts.label }} </div>
        <div class="col-md-6"><input id="event_starts" type="datetime-local" value="2014-10-31T00:00:01"> {% for error in form.event_starts.errors %} <div class="flash">{{ message }}</div>{% endfor %}</div>
    </div>
    <div class="row">
        <div class="col-md-6">{{ form.event_ends.label }} </div>
        <div class="col-md-6"><input id="event_ends" type="datetime-local" value="2014-10-31T00:00:01"> {% for error in form.event_ends.errors %} <div class="flash">{{ message }}</div>{% endfor %}</div>
    </div>
    <div class="row">
        <div class="col-md-6">{{ form.price.label }} </div>
        <div class="col-md-6">{{  form.price() }} {% for error in form.price.errors %} <div class="flash">{{ message }}</div>{% endfor %}</div>
    </div>
    <div class="row">
        <div class="col-md-6">{{ form.cuisine_type.label }} </div>
        <div class="col-sm-2 control-label" for="formGroupInputLarge">{{  form.cuisine_type() }} {% for error in form.cuisine_type.errors %} <div class="flash">{{ message }}</div>{% endfor %}</div>
    </div>
        {% with messages = get_flashed_messages() %}
        {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
            <li>{{ message | safe }}</li>
        {% endfor %}
        </ul>
      {% endif %}

    {% endwith %}


    <button type="submit" class="btn btn-primary btn-lg" value="submit">Submit</button>

</form>

2、解决方案

为了解决这个问题,需要在 DateTimeField 中使用 format 参数来指定日期时间的格式。 修改后的表单代码如下:

class FoodForm(Form):
    food_name = StringField('Food Name', validators=[Required()])
    food_description = StringField('Food Description', validators=[Required()])
    price = FloatField('Price', validators=[Required()])
    event_starts = DateTimeField('Event Starts', format ='%Y-%m-%dT%H:%M:%S', validators=[Required()])
    event_ends = DateTimeField('Event Ends', format ='%Y-%m-%dT%H:%M:%S',validators=[Required()])
    food_types = ['Indian', 'American', 'Chinese', 'Italian', 'Other', 'French',
                  'Deli','Mediterranean', 'Japanese']
    food_choices = [(i+1, food_type) for i, food_type in enumerate(sorted(food_types))]
    cuisine_type = SelectField('Cuisine Type', choices=food_choices, validators=[Required()])
    submit = SubmitField('Submit')

修改后的 Jinja 模板代码如下:

<form class="form form-horizontal" role="form" method="POST">
    {{ form.hidden_tag() }}
    <div class="row">
        <div class="col-md-6">{{ form.food_name.label }} </div>
        <div class="col-md-6">{{  form.food_name() }} {% for error in form.food_name.errors %} <div class="flash">{{ message }} </div>{% endfor %}</div>
    </div>
    <div class="row">
        <div class="col-md-6">{{ form.food_description.label }} </div>
        <div class="col-md-6">{{  form.food_description() }} {% for error in form.food_description.errors %} <div class="flash">{{ message }}</div>{% endfor %}</div>
    </div>
    <div class="row">
        <div class="col-md-6">{{ form.event_starts.label }} </div>
        <div class="col-md-6">{{  form.event_starts(type="datetime-local") }} {% for error in form.event_starts.errors %} <div class="flash">{{ message }}</div>{% endfor %}</div>
    </div>
    <div class="row">
        <div class="col-md-6">{{ form.event_ends.label }} </div>
        <div class="col-md-6">{{  form.event_ends(type="datetime-local") }} {% for error in form.event_ends.errors %} <div class="flash">{{ message }}</div>{% endfor %}</div>
    </div>
    <div class="row">
        <div class="col-md-6">{{ form.price.label }} </div>
        <div class="col-md-6">{{  form.price() }} {% for error in form.price.errors %} <div class="flash">{{ message }}</div>{% endfor %}</div>
    </div>
    <div class="row">
        <div class="col-md-6">{{ form.cuisine_type.label }} </div>
        <div class="col-sm-2 control-label" for="formGroupInputLarge">{{  form.cuisine_type() }} {% for error in form.cuisine_type.errors %} <div class="flash">{{ message }}</div>{% endfor %}</div>
    </div>
        {% with messages = get_flashed_messages() %}
        {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
            <li>{{ message | safe }}</li>
        {% endfor %}
        </ul>
      {% endif %}

    {% endwith %}


    <button type="submit" class="btn btn-primary btn-lg" value="submit">Submit</button>

</form>

现在,就可以正常使用 form.validate_on_submit() 来验证表单了。

通过这些步骤,我们可以在 Flask 应用中有效地使用日期和时间组件,提高表单的可用性和功能性。