Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WTForms - DateTimeLocalField data is None after submit

After form is submitted with a POST request, every Field data has its value, except DateTimeLocalField. Accessing DateTimeLocalField's data value is a type of None.

Form

class ArticleForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    category = SelectField(u'Category', choices=categories.choices)
    town = StringField('Town', validators=[DataRequired()])
    minimal_price = IntegerField('Minimal price')
    article_image = FileField('Article_image', validators=[FileRequired()])
    time_left = DateTimeLocalField('Time to end', validators=[InputRequired()],
                              format='%Y-%m-%d %H:%M:%S')
    description = TextAreaField('Description', validators=[DataRequired()])

Validation: (tested with is_submitted, all work except for article_form.time_left.data which is None)

if article_form.validate_on_submit():

    new_article = Article(name=article_form.name.data,
                          category=article_form.category.data,
                          town=article_form.town.data,
                          minimal_price=article_form.minimal_price.data,
                          article_image=name,
                          time_left=article_form.time_left.data, # <-- None
                          description=article_form.description.data,
                          user_id=current_user.id)

Any help to get data from DateTimeLocalField ?

like image 554
Dinko Pehar Avatar asked Jan 02 '23 17:01

Dinko Pehar


2 Answers

Try changing the format of the DateTimeLocalField from

format='%Y-%m-%d %H:%M:%S' 

to:

format='%Y-%m-%dT%H:%M'

Tip: you can print the actual content of the input field prior to the validation to confirm the correct formatting of the DateTimeLocalField field.

like image 71
Nikolay Petrov Avatar answered Jan 04 '23 08:01

Nikolay Petrov


Use wtforms.fields.html5.DateTimeLocalField instead of wtforms.DateTimeLocalField. Set the format with date and time separated by a 'T'. If you would want the current time as the default value, set default parameter.

from wtforms.fields.html5 import DateTimeLocalField

class InterviewForm(Form):
    posted = DateTimeLocalField('Posted:', default=datetime.today, format='%Y-%m-%dT%H:%M')
like image 25
easai Avatar answered Jan 04 '23 06:01

easai