DatePickerWidget with Flask, Flask-Admin and WTforms

蹲街弑〆低调 提交于 2019-11-29 21:53:37

As davidism says in the comments, the default DateField just provides date parsing, it'll just be displayed as a normal text-input.

If you're ready to fully embrace html5 then you can use the DateField from wtforms.fields.html5 which will render a datepicker in any browser that supports it:

from flask import Flask, render_template
from flask_wtf import Form
from wtforms.fields.html5 import DateField
app = Flask(__name__)
app.secret_key = 'SHH!'


class ExampleForm(Form):
    dt = DateField('DatePicker', format='%Y-%m-%d')


@app.route('/', methods=['POST','GET'])
def hello_world():
    form = ExampleForm()
    if form.validate_on_submit():
        return form.dt.data.strftime('%Y-%m-%d')
    return render_template('example.html', form=form)


if __name__ == '__main__':
    app.run(debug=True)

The more usual approach is to find a nice datepicker online, that's using CSS and JS to handle it's display and include that code into your html template, and tell it to apply the datepicker style to any html element that has a class of datepicker. Then when you generate your form you can just do:

<!-- all your CSS and JS code, including the stuff -->
<!-- to handle the datepicker formatting -->

<form action="#" method="post">
    {{ form.dt(class='datepicker') }}
    {{ form.hidden_tag() }}
    <input type="submit"/>
</form>

Any attributes (that aren't reserved for other use) you pass into rendering the form element will by default just add it as an attribute, for example the {{ form.dt(class='datepicker') }} will generate <input class="datepicker" id="dt" name="dt" type="text" value=""> so your CSS/JS can then do whatever it needs to do to provide a good interface for your user.

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