Passing radio button value on page refresh in Flask - python

I am trying to build a simple Flask app in Python with two radio buttons and a "refresh" button, where, on clicking on the refresh button, the page reloads and displays the radio button selection on the previous page.
Routes.py:
#app.route("/")
def display():
return render_template("index.html", choice=choice)
if request.form['submit'] == 'Refresh':
choice= request.form.get("Choice")
return redirect(url_for('/'))
index.html:
<html>
<head>
<title>Choice</title>
</head>
<body>
<h2>Choice</h2>
<hr>
{{choice}}<br>
<form action="">
<input type="radio" name="Choice" value="Choice1"><span>Choice 1/span><br/>
<input type="radio" name="Choice" value="Choice2"><span>Choice 2</span>
<input type="submit" name="refresh" value="Refresh">
</form><br>
</form> </body>
</html>

Apply the below changes and check if it works!
render_template, request, redirect, url_for was used but not imported. Try to import them.
from flask import Flask, render_template, request, redirect, url_for
To retrieve POST data, you can use request.form.
To retrieve GET data, you can use request.args.
Try the below code if you want to use request.args:
#app.route("/")
def display():
choice = request.args.get('Choice','None Selected')
return render_template("index.html", choice=choice)
if request.args.get('refresh') == 'Refresh':
return redirect(url_for('display',Choice=choice))
Try the below code if you want to use request.form:
#app.route("/",methods = ['POST', 'GET'])
def display():
if request.method == 'GET':
choice = request.args.get('Choice','None Selected')
return render_template("index.html", choice=choice)
if request.method == 'POST':
choice= request.form.get("Choice")
return redirect(url_for('display',Choice=choice))
In index.html add <form action="" method="POST"> to send the form data

Related

need help to display value in a form for html

I need to display the value that was entered in a form after the user clicks the submit button. It displays it for a split second but when the page reloads it's gone
<html>
<html>
<head>
<link rel="stylesheet" href="{{url_for('static',filename='main.css')}}">
</head>
<body>
<title> Patent Info </title>
<form action="" method="POST" >
Enter Room Number <input type="number" name="getInput" id="data" min="1" max="5">
<input type="submit" onclick="c.value = getInput.value">
<h4>Going to Room: <output name="c"></output></h4>
</form>
from flask import Flask, render_template, request
from random import randrange
app = Flask(__name__)
#app.route("/")
def main():
return render_template('index.html')
#app.route('/', methods=['POST'])
def my_form_post():
input_nopol = request.form['getInput']
if request.method == 'POST':
with open('nopol.txt', 'w') as f:
f.write(str(input_nopol))
return render_template('index.html', nopol=input_nopol)
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=80)
I know i can do it if i change from type submit to type button but then my POST method dose not work
Try This
<h4>Going to Room: <output name="c">{{ nopol }}</output></h4>
Just add this below <h4>Going to Room: <output name="c"></output></h4>
<p>{{ nopol }}</p>

Executing python script with flask, from button

I'm trying to execute a def/python script from flask, when clicked on button... but can't seem to figure it out.
Here's my Python Code
from flask import Flask, redirect, url_for, render_template, request
import webbrowser
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
def contact():
if "open" in request.form:
print("Test")
elif "close" in request.form:
print("Test 2")
return render_template('contact.html')
if __name__ == "__main__":
app.run(debug=True)
And here is my HTML Code
<html>
<head>
<title>Home page</title>
</head>
<body>
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h1>Test</h1>
<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">
{% endblock %}
</body>
</html> ```
I don't know what is in {% block content %} but you need to have a form in order to call backend where you provide the url route that you want to call and the method you want to use (usually with forms it's POST). Also in the /contact endpoint you need to provide #app.route('/contact') and that it would accept POST request #app.route('/contact', methods=['POST']). Modify your python and HTML to look like this:
from flask import Flask, redirect, url_for, render_template, request, jsonify
import webbrowser
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
#app.route('/contact', methods=['POST'])
def contact():
result = False
if "open" in request.form:
result = activate_lamp() # expecting True as a result of function
elif "close" in request.form:
result = deactivate_lamp()
return jsonify({'result': result}) # expecting True as a result of function
if __name__ == "__main__":
app.run(debug=True)
<html>
<head>
<title>Home page</title>
</head>
<body>
<h1>Test</h1>
<form action="{{ url_for('contact') }}" method="post">
<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">
</form>
</body>
</html>
The jsonify will return an object to the front end with default 200 response code. Then you can either do something with it or ignore it. The idea is that in the route you can call other functions, but you must return a valid HTTP response to the front-end, e.g. jsonify, or plain return '', 200 might be enough.

Flask : Why does not the HTML submit button redirect the page to the target URL?

I'm new to Flask. This is the content of my login.html file:
<html>
<body>
<form action="localhost:5000/login" method="POST">
<p>Enter name : </p>
<p><input type = "text" name="nm"/></p>
<p><input type = "submit" value="submit"/></p>
</form>
</body>
</html>
This is app.py file:
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
#app.route('/success/<name>')
def success(name):
return "Welcome %s" % name
#app.route('/login', methods = ['POST', 'GET'])
def login():
if request.method == 'POST' :
user = request.form['nm']
return redirect(url_for('success', name = user))
else :
user = request.args.get('nm')
return redirect(url_for('success', name = user))
if __name__ == "__main__":
app.run(debug = True)
When I entered a text in my HTML login form and click the submit it should have redirected to the desired URL but nothing happened.
Edit
After trying with changes suggested by Rogan Josh, i got this error:
File not found
Firefox can’t find the file at /home/hp/flask_practice/{{ url_for('login') }}.
Check the file name for capitalization or other typing errors.
Check to see if the file was moved, renamed or deleted.
Your code can't do anything because you haven't actually served the html from your flask application. You've just double-clicked it and opened the HTML in a browser.
Your html file needs to go in a subdirectory from app.py called "templates". Then change your code to:
from flask import Flask, redirect, url_for, request, render_template
app = Flask(__name__)
#app.route('/success/<name>')
def success(name):
return "Welcome %s" % name
#app.route('/login', methods = ['POST', 'GET'])
def login():
if request.method == 'POST' :
user = request.form['nm']
return redirect(url_for('success', name = user))
else :
user = request.args.get('nm') # THIS DOES NOTHING
return render_template('login.html') # CHANGED HERE
if __name__ == "__main__":
app.run(debug = True)
You should also update your HTML to:
<html>
<body>
<form action="{{ url_for('login') }}" method="POST">
<p>Enter name : </p>
<p><input type = "text" name="nm"/></p>
<p><input type = "submit" value="submit"/></p>
</form>
</body>
</html>
Now open the browser and go to 127.0.0.1:5000/login

Python Flask: clicking button doesn't do anything

I am new to Flask and I'm trying to build a simple web app. Basically what I have on the home page is a text input box and a submit button.
After clicking submit, it shows some result based on the text that was inputted (for now it's hardcoded in the code below) and also 2 buttons (positive/negative) to add the inputted text to a specific file (either with a "positive" or "negative" label).
However, the problem I face is with these 2 buttons: they don't do anything when clicked.
Here is what I have for now:
The Python Flask app
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
#app.route('/process-data', methods=['GET', 'POST'])
def process_data():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST':
# get the text from the form that was filled in
input_text = request.form['text']
# if submit button is clicked
if request.form['submit'] == 'Submit':
final_result = 'stackoverflow is the best'
if request.form['submit'] == 'Positive':
f = open('dataset/dataset.tsv', 'a')
f.write(input_text + '\t' + 'positive')
# if negative button is clicked
if request.form['submit'] == 'Negative':
f = open('dataset/dataset.tsv', 'a')
f.write(input_text + '\t' + 'negative')
# show the result on the page
return render_template('index.html', result=final_result, text=input_text)
The index.html file
<!doctype html>
<form action="/process-data" method="post" role="form">
<label for="text">Text:</label>
<input type="text" name="text" placeholder="Input sentence here">
<input type="submit" name="submit" value="Submit">
</form>
{% if result is not none %}
{{ result }}
<h2>Add to dataset</h2>
<form action="/process-data" method="post" role="form">
<label for="add-dataset">This sentence was:</label>
<input type="submit" name="submit" value="Positive">
<input type="submit" name="submit" value="Negative">
</form>
{% endif %}
</html>
Create your / route and have it simply return the index template and nothing else like this:
#app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
Then assign the other route to another function which will do the processing. I wouldn't call it index, maybe something like process-data, like this:
#app.route('/process-data', methods=['GET', 'POST'])
def process_data():
# put the body of your function here
# ...
# ...
# ...
return render_template('index.html', result=final_result, text=input_text)
Finally, you just need to update your form action accordingly:
<form action="/process-data" method="post" role="form">
Check whether you have set the configuration setting SESSION_COOKIE_SECURE. If you're working in localhost or through an unsecure line and you have set SESSION_COOKIE_SECURE=True then no session cookie will be sent and as such no forms, csrf protection and various other operations will work. Instead use SESSION_COOKIE_SECURE=False under these circumstances.

How to pass your POST to another URL using Flask

I am trying to get some phrase from the user, and when he/she will press "submit" i want to redirect him/her to another page with his/her name, using Flask. Here is my Python code:
from flask import Flask, redirect, render_template, request, session, url_for
app = Flask(__name__)
#app.route("/", methods = ["POST", "GET"])
def login():
if request.method == "POST":
user = request.form["name"]
return redirect(url_for("success", name=user))
else:
return render_template("login.html")
#app.route("/success", methods = ["POST", "GET"])
def success():
user = request.form.get('name')
return render_template("success.html", name=user)
if __name__ == "__main__":
app.run("0.0.0.0", 8080)
So when i go to my site i am going to "else" branch and do: "render_template("login.html")". Then if i press submit i go into "if" where i am trying to redirect the user to "success.html". Here is my login.html:
<html>
<body>
<form action = "http://ide50-zahar-zagrava.cs50.io:8080/" method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "name" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
And succes.html:
<html>
<body>
<h1>Hello {{ name }}!</h1>
</body>
</html>
But insted of saying: "Hello " it says: "Hello None".
My main question is how to pass data from one page to another?
I am completely new at Flask and Python, so i can't figure out what's going wrong.
your action from form is wrong.you are sending the form to the index page. you could edit it like:
<form action="{{ url_for('success') }}" method="post">
this way, your form will be sent to the success method.

Categories