This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 4 years ago.
I want to make an if statement that deals with the case when a user doesn't select any radio options. if they don't select a radio option, it just prints out an error message. However, every time I don't select an option it just tells me:
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'mysearch'
HTML:
<form class="anotherform" method="POST">
<div class="myform">
<input type="text" placeholder="Enter your text or leave empty" name="search_term">
</div>
<input type="radio" name="mysearch" value="option1">Option 1<br>
<input type="radio" name="mysearch" value="option2">Option 2<br>
<input type="radio" name="mysearch" value="option3">Option 3<br>
<input type="radio" name="mysearch" value="option4">Option 4<br>
<button class="button" type="submit">Search</button>
</form>
{{error_msg}}
routes.py
#app.route('/search', methods=['POST', 'GET'])
def search():
if request.method == 'POST':
search_filter = request.form["mysearch"]
search_term = request.form["search_term"]
if search_filter == "":
error_msg = 'You didnt select an option'
return render_template('/search.html', error_msg=error_msg)
return render_template('/search.html')
If I'm not mistaken request.form is a Multidict type which is like a Python dictionary.
So you can get a default value from dictionary if you are not sure if the key exists, and avoid throwing the error in your application like this:
search_filter = request.form.get("mysearch", "")
search_term = request.form.get("search_term", "")
And then check search_filterif it is empty or it has value.
Related
This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
#app.route('/signup',methods=["GET","POST"])
def signup():
return render_template('signup.htm')
password = request.form['password']
if password =="python":
return redirect(url_for("home"))
This is my python code for retrieving form input and then to redirect the user to the home page if the password is "python".
<form action="#" method="POST" name="password">
<input type="password" class="form-control"
id="exampleFormControlInput1" placeholder="Password">
</form>
This is the respective HTML code for the signup page.
you are using name="password" in your form attributes which is wrong. You have to use it in attributes of input
So HTML should be like this
<form action="#" method="POST"><input type="password" name="password" class="form-control" id="exampleFormControlInput1" placeholder="Password"></form>
Also in python you are returning first which is also wrong return is last statement of function
So python code must be like this
#app.route('/signup',methods=["GET","POST"])
def signup():
if(requset.method == 'POST'):
password = request.form['password']
if password =="python":
return redirect(url_for("home"))
else:
return render_template('signup.htm')
This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
I have been working with flask for a long while, but after a break from it, I cant seem to figure out what's wrong here.
index.html:
<input name="linkHolder" type="url" class="defaultTextBox advancedSearchTextBox link" placeholder="http://www.youtube.com">
<form method="POST" action="/button">
<input class="btn" type="submit">Go</input>
</form>
main.py:
#app.route('/button', methods=["GET", "POST"])
def button():
if request.method == "POST":
dlink = request.form.get("linkHolder")
print(dlink)
return render_template("index.html", dlink=dlink)
I'm sorry if its a simple answer but my end goal here is to load the link typed by the user, print said link, and then reload the page. What am I doing wrong?
In your index.html, your <form> tag does not include the linkHolder input.
Do the following:
<form method="POST" action="/button">
<input name="linkHolder" type="url" class="defaultTextBox advancedSearchTextBox link" placeholder="http://www.youtube.com">
<input class="btn" type="submit">Go</input>
</form>
You might also need an if statement in main.py that actually renders the page
#app.route('/button', methods=["GET", "POST"])
def button():
if request.method == "GET":
return render_template("index.html")
if request.method == "POST":
dlink = request.form.get("linkHolder")
print(dlink)
return render_template("index.html", dlink=dlink)
You need a form with the name
Also, your tag </input> input doesn't have any closing tag you should be using button tag
<form method="POST" action="/button">
<input type="text" name="linkHolder">
<button class="btn" type="submit">Go</button>
</form>
I am new at this and trying to submit a basic form which has a dropdown list and 2 text fields. The lists value is the path of the flask route which needs to be submitted the data.
Depending on the item the user selects from the list, i would like to submit the form with data to that url, eg if user selects "a" then i would like to submit form to http://url/url1. How can this be done?
<form action="" class="form1" method="get">
<select class="form-control" id="function" name="cars">
<option value="/url1">a</option>
<option value="/url2">b</option>
<option value="/url3">c</option>
</select>
<input class="form-control" type="number" name="number1" value="">
<input class="form-control" type="number" name="number2" value="">
<input class="form-control" type="submit">
</form>
I have python flask code on server :
#app.route("/url1")
def url1():
num1=request.args.get('number1',default=-1,type=int)
num2=request.args.get('number2',default=-1,type=int)
evaluate the numbers and return render_template()
#app.route("/url2")
def url2():
num1=request.args.get('number1',default=-1,type=int)
num2=request.args.get('number2',default=-1,type=int)
evaluate the numbers and return render_template()
if i understand your question , you can solve it by jquery
code sample
$("#function").change(function() {
var action = $(this).val();
$("#form1").attr("action",action);
});
or
you can set a default action for the form and then in route do according to the selected value
I used redirection in app.py to resolve this
<form action="/submit" class="form1" method="get">
and then
#app.route('/submit', methods=['GET'] )
def submit():
num=request.args.get('number1',default=-1, type=int)
return redirect(url_for('url1', m=num))
#app.route("/url1")
def url1():
evaluate the numbers and return render_template()
I am trying to print off the checkbox value in Flask when I hit the submit button.
app.py snippet:
#app.route('/test2', methods=['GET', 'POST'])
def test2():
if request.method == "POST":
if request.form['submit'] == 'submit':
print(request.args.get('check'))
return render_template('test.html')
HTML:
<div class="container"><br>
<form role="form" method="post">
<input type="checkbox" name="check" value="test">
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</div>
It returns 'None' when I hit the submit button.
I have also tried request.form.get()
#app.route('/test2', methods=['GET', 'POST'])
def test2():
if request.method == "POST":
if request.form['submit'] == 'submit':
print(request.form.get('check'))
return render_template('test.html')
That also returns 'None'.
When submitting an HTML form, unchecked checkboxes do not send any data. On Flask's side, there will not be a key in form, since no value was received. If you want to check if a single checkbox (with a unique name) is checked, just test if it's name is in form. If you want to check which of multiple checkboxes (with the same name, but different values) are checked, use getlist instead.
One boolean:
<input type="checkbox" name="check">
checked = 'check' in request.form
Multiple options:
<input type="checkbox" name="check" value="1">
<input type="checkbox" name="check" value="2">
<input type="checkbox" name="check" value="3">
selected = request.form.getlist('check')
any_selected = bool(selected)
I have a form like this:
<form method="post" action="/addReceiverHandler" id="addReceiverForm">
<label for="title">name:</label>
<input type="text" name="title" value="name"/><br>
<label for="dimmer">Dimmer:</label>
<input type="text" name="dimmer" value="True"/><br>
<input type="submit" value="sync" />
</form>
And I recive the answer with:
#app.route('/addReceiverHandler', methods=['POST', 'GET'])
def addReceiverHandler():
if request.method == 'POST':
print request.form
But the strange thing is that the input field "title" arrives with value "name" but that's it. The second input does not arrive, why is that?
Never mind! Stupid hidden jQuery.
I had set a preventDefault behaviour in jQuery and submitting that way, seems like I've forgotten that...