I have a flask app that I am trying to append a url parameter to after a form submission. For example, I have a date input as a form, and if I selected 2022-02-17 and pressed the button to submit, I would want the url to then append ?date=2022-02-17
. My problem is the its always 1 behind. So on first submit, it is only ?date=
, and then if I chose another date that isn't 2022-02-17, the url would then update to ?date=2022-02-17
. I have a print to make sure the date is being correctly passed into the handler function for that page as well.
Here is a jinja snippet of the form:
<div >
<p>{{ search_date }}</p>
<form action={{ url_for('past_releases', date=search_date) }} method="POST">
<div >
<div >
<input type="date" id="searchdate" name="searchdate">
</div>
<button type="submit" >
<i ></i>
</button>
</div>
</form>
</div>
and here is the python function for handling that page:
@app.route("/past-releases", methods=["GET", "POST"])
def past_releases():
"""
Search for past releases' info, based on date.
"""
search_date = None
if request.method == "GET" and request.args.get("date"):
search_date = request.args.get("date")
elif request.method == "POST":
search_date = request.form["searchdate"]
# # we use a try here for when someone might click search on the placeholder
# # date of "mm/dd/yyyy"
print(search_date)
if search_date:
try:
date_selcted = dateutil.parser.parse(search_date).strftime("%B %d, %Y")
except ParserError:
return render_template("past_releases.jinja")
pipelines_and_tasks = get_pipeline_runs_by_date(search_date)
return render_template(
"past_releases.jinja",
date_selected=date_selcted,
pipelines_and_tasks=pipelines_and_tasks,
search_date=search_date,
)
return render_template("past_releases.jinja")
CodePudding user response:
I think you should replace the "method" parameter of the form with the GET method. The parameter in url_for
is then no longer required. The selected date is automatically added as a URL parameter when the form is submitted.
In the query using request.args
, it is also possible to add a standard parameter as the second argument and, specifying the parameter name type, a function to convert the parameter to a date.
The example below illustrates the described possibility.
Flask (app.py)
from datetime import date
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/search')
def search():
search_date = request.args.get(
'search-date',
date.today(),
type=date.fromisoformat
)
# Your filter function here.
return render_template('search.html', **locals())
HTML (templates/search.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Search</title>
</head>
<body>
<form method="get">
<input type="date" name="search-date" value="{{search_date.isoformat()}}" />
<input type="submit" />
</form>
</body>
</html>