Search code examples
pythondatetimeflasknullnonetype

Python Flask - How to set a default value of NULL for type Date in a form


I have an HTML form to update field values. Within this form, I have a field called app_deadlines, which is of type Date:

my_data.app_deadlines = datetime.datetime.strptime(request.form['app_deadlines'], "%Y-%m-%d")

If I leave that field empty and press the submit button to update, it throws the error shown below.

ValueError: time data '' does not match format '%Y-%m-%d'

^^Therefore, the database update doesn't occur.

In essence, it won't leave the attribute as NULL (which is how it's stored in my SQLite database table) when I update, so how do I set it so that it accepts NULL? It won't let me do or None, which worked for another field:

my_data.cfda_no = request.form['cfda_no'] or None

What could the default NULL value for type Date be so that it's still stored in the format '%Y-%m-%d'?

Class View:

class FundingSource(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    complete = db.Column(db.String(10), default=False, nullable=False)
    department = db.Column(db.String(100), nullable=False)
    agency = db.Column(db.String(150), nullable=False)
    cfda_no = db.Column(db.Float(), nullable=True)
    app_deadlines = db.Column(db.Date(), nullable=True)

Flask View:

@main.route("/update", methods=['GET', 'POST'])
def update():
    if request.method == 'POST':
        my_data = FundingSource.query.get(request.form.get('id'))

        my_data.complete = request.form['complete']
        my_data.department = request.form['department']
        my_data.agency = request.form['agency']
        my_data.cfda_no = request.form['cfda_no'] or None
        my_data.app_deadlines = datetime.datetime.strptime(request.form['app_deadlines'], "%Y-%m-%d")

Any help is appreciated! Thanks!


Solution

  • It looks like you are getting an error when no date is provided, so you want to be able to handle receiving both date and None values. Because datetime.datetime.strptime() only accepts date values, you can add a logic check to handle None values by using an inline statement:

    my_data.expiration_funds = datetime.datetime.strptime(request.form['expiration_funds'], '%Y-%m-%d') if request.form['expiration_funds'] else None