-2

I am getting BadValueException error on Flask with the usage of Flask and MongoAlchemy. The issue I am having is requesting POST data from date. I tried encoding to UTF8, however is returning string, instead being instance of datetime.datetime.

Error:

BadValueException: Bad value for field of type "date_deadline". Reason: "Value is not an instance of <type 'datetime.datetime'> (got: str)".

Python

app = Flask(__name__)
db = MongoAlchemy(app)

class Model(db.Document):
    name = db.StringField()
    date_added = db.DateTimeField()

@app.route('/form', methods=['GET', 'POST'])
def form():
    if request.form.get('submit'):
        get_name = request.form.get('name')
        get_date = request.form.get('date').encode('utf8')

        new_model = Model(name = get_name, date = get_date)
        new_model.save()
    return render_template('form.html')

HTML

<label for="name">Name</label>
<input type="text" name="name">

<label for="date">Date</label>
<input type="datetime-local" name="date">
IntFooBar
  • 174
  • 3
  • 18

2 Answers2

1

You can use the dateutil module to convert the string date to datetime type

from dateutil import parser

get_date = parser.parse(request.form.get('date'))
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

The data coming in from the form is already a string. What you need to do is convert it to a datetime format.

https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime

I don't know how your datetime string is formatted, but assuming it's something like yyyy-mm-dd, then your conversion might look like this:

get_date = datetime.strptime(request.form.get('date'), '%Y-%m-%d')
burling
  • 409
  • 2
  • 5