5

How should a date picker be implemented when using Flask-wtf?

Have attempted using various examples from the web but none seem to work.

See code for latest attempt.

from flask import Flask, render_template, session, redirect, url_for, flash
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import FlaskForm, Form
from wtforms.fields.html5 import DateField
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from wtforms.fields import DateField
from flask_datepicker import datepicker

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'

bootstrap = Bootstrap(app)
moment = Moment(app)

class LoginForm(FlaskForm):
    entrydate = DateField('entrydate')
    submit = SubmitField('Submit')


@app.route('/date', methods=['GET', 'POST'])
def datep():
    form = LoginForm()
    if form.validate():
        return 'Form Successfully Submitted!'
    return render_template('date.html', form=form)

The template file:

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Flasky{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Hello, select date!</h1>
</div>
{{ wtf.quick_form(form) }}
{% endblock %}

Expected: to see drop down date selector.

Actual: date selector is not displayed.

user45097
  • 561
  • 2
  • 7
  • 16
  • use accepted answer from https://stackoverflow.com/questions/26057710/datepickerwidget-with-flask-flask-admin-and-wtforms – Andrew Allen Mar 29 '19 at 14:46
  • plus you have two imports with names of `DateField`. pick one or use an `as` to rename – Andrew Allen Mar 29 '19 at 14:51
  • @AndrewAllen, thanks for the pointers. I removed the 2nd `datefield` import and this has resolved the issue. There is now a drop down calendar. – user45097 Mar 29 '19 at 17:35

1 Answers1

2

In FlaskForm it would be as follows:

    #Import the resource from wtforms.fields.html5
    from wtforms.fields.html5 import DateField,DateTimeField 
   
    class LoginForm(FlaskForm):
    entrydate = DateField('entrydate', format='%Y-%m-%d' )
    submit = SubmitField('Submit')

You can try putting the following in html:

<div class="page-header">
    <h1>Hello, select date!</h1>
 {{form.entrydate (class= "datepicker")}}
</div>

With the rest of the HTML5 it's like this:

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Flasky{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Hello, select date!</h1>
    {{form.entrydate (class= "DateTimeField")}}

</div>
{{ wtf.quick_form(form) }}
{% endblock %}
IT Cafe
  • 21
  • 3
  • `from wtforms.fields.html5` should be `from wtforms.fields` now. ( https://stackoverflow.com/a/70200622/503621 ) – B. Shea May 20 '22 at 23:02