Search code examples
pythonhtmlflaskjinja2

How to pass value to HTML date input using Flask/Jinja2


I'm trying to set the value of an HTML input element (type=date) by passing the value from my view.py file.

index.html

<div class="date-input">
    <label for="start_date">Choose a start date:</label><br>
    <input type="date" name="start_date" value="{{ start_date }}"><br>
</div>

views.py

@views.route('/')
def index(): 
    # Set the start_date to today.
    start_date = datetime.datetime.now().strftime("%x")

return render_template('index.html', start_date=start_date)

To troubleshoot, when I print(start_date) I do get today's date (12/05/2022).


Solution

  • The HTML input element (type=date) will only accept a date in the format yyyy/mm/dd. Edit the variable in the python file:

    start_date = datetime.datetime.now().strftime("%Y-%m-%d")