Can't Retrieve Variable From Url With Flask App After Submitting Search Form
I would like to present a new view after the user submits a search form. I made it as the same way as I do with my other views, but unfortunately this time doesn't happens anything
Solution 1:
You're confusing url parameters, which are captured with <variable>
, with query parameters, which are accessed in request.args
. Remove the query parameter from your route definition and access it in the view.
from flask import request
@app.route('/')defindex():
return render_template('index.html')
@app.route('/search')defsearch():
search = request.args.get('search') # will be None if form wasn't submitted# do something with searchreturn render_template('search.html', search=search)
index.html
:
<formaction="{{ url_for('search') }}"><inputname="search"/><inputtype="submit"value="Search"/></form>
Solution 2:
You have several mistakes. First you are incorrectly specifying the route on the server side. You can't capture or specify query parameters on the flask route. You can have something like
@app.route('/search')
Secondly you need to provide an action and method on your form. So
<form action="{{ url_for("search") }}" method="POST">
If you don't specify the method, it will be sent as a GET, and the fields will appear as query arguments. If you do a post then you can retrieve the fields like so on the server side:
request.form['inputSearch']
I introduced the /search route, but you could do the same from the root "/".
Post a Comment for "Can't Retrieve Variable From Url With Flask App After Submitting Search Form"