maximesunnen / CS50x

CS50x - Introduction to Computer Science (Final project)
1 stars 0 forks source link

Unexpected auto-formatting of datetime object #2

Open maximesunnen opened 11 months ago

maximesunnen commented 11 months ago

forms.py:

from flask_wtf import FlaskForm
from wtforms import DateField

class testForm(FlaskForm):
     birthday = DateField()

app.py:

     from forms.py import testForm
     from flask import render_template

    @app.route("/issue", methods=["GET", "POST"]):

      # Form
      test_form = testForm()

      # Extract form data
      form_data = form.data
      return render_template("issue.html", form_data=form_data)

test.html:

    {% if form_data["birthday"] %}
           <input class="form-control" id="birthday" name="birthday" type="date" value={{form_data["birthday"]}}>
    {% else %}
           {{ test_form.birthday() }}
    {% endif %}

Issue description

'birthday': datetime.date(1111, 11, 3)

So birthday is a datetime.date object.

{{ test_data["birthday"] }}

I see the following inside my app:

"Sun, 11 Nov 0001 00:00:00 GMT"

And in the developer tools:

<input class="form-control" id="birthday" name="birthday" type="date" value=Sun, 11 Nov 0001 00:00:00 GMT> The specified value "Sun," does not conform to the required format, "yyyy-MM-dd".

I do not understand why form_data["birthday"] is not considered a datetime.date object anymore? Why is the time added? Why is it converted to a string? This is causing the problem that I'm not able to maintain the birthday input from the user across multiple requests (i'm saving form data temporarily inside session).

maximesunnen commented 11 months ago

The following line solves the issue:

session["form_user_data"]["birthday"].strftime("%Y-%m-%d")

Still not satisfying because the "%Y-%m-%d"format should be the default and is not changed anywhere.