This question already has answers here:
How to pass a variable between Flask pages?
(2 answers)
Closed 1 year ago.
Trying to get two variables via a html form that will be used in other functions later in the code. For now i just want to print the two variables as a test
index.html is:
<html>
<form action="{{ url_for("user_input")}}" method="post">
<label for="a_site">A Site:</label>
<input type="text" id="a_site" name="a_site" placeholder="a_site">
<label for="z_site">Z Site:</label>
<input type="text" id="z_site" name="z_site" placeholder="z_site">
<button> Submit </button>
</form>
</html>
results.html is:
<html>
<body>
{{ a_site_name }} <br>
{{ z_site_name }}
</body>
</html>
Python code
from flask import Flask,render_template,request
app = Flask(__name__)
#app.route('/', methods =['GET', 'POST'])
def user_input():
a_site_name = request.form.get('a_site')
z_site_name = request.form.get('z_site')
return render_template('index.html')
#app.route('/results')
def results():
return render_template('results.html',
a_site_name=a_site_name,
z_site_name=z_site_name
)
def main():
app.run(host='localhost', port=8080)
if __name__ == "__main__":
main()
When i click "Submit" in the browser i get a 500 error, in the flask console the error is NameError: name 'a_site_name' is not defined which makes sense since the results function doesn't know what those two vars are...
I'd usually do something like
a_site_name, z_site_name = user_input() under my main function but that doesn't seem to work either...
So how can i get this to work? Those two vars will end up being used to do a bunch of other python functions which will be invisible to the user, with the end results being displayed on the browser
I think you mismatched form action attribute and href in submit button. Your form is POST-ed to the action URL but then you go to results URL and there is no form posted there.
Related
I'm trying to create a dynamic URL based on user's input from an HTML form.
For example, if a user types in 'AAPL' or 'KO', the next page should be:
webapp.com/result/AAPL or webapp.com/result/KO
index.html:
<div class="cell" id="cell-1-2">
<span class="data" style="text-align: center;">
<form action="{{ url_for('ticker_result', variable='variable') }}" method="POST">
<input type="text" name="variable" placeholder="search ticker or company" maxlength="4"
font-size="24px" style="text-transform:uppercase">
<input class="button" type="submit" value="Search" onclick="tickerSymbol();">
</form>
</span>
</div>
I've tried renaming the 'variable' part to several different things and nothing works so I'm just stuck at this point.
main.py:
# Routing to the homepage
#app.route("/")
def markert_hours_today():
return render_template(
"index.html")
# Routing to the result page
#app.route("/result/<variable>", methods = ["GET", "POST"])
def ticker_result(variable):
if request.method == "POST":
result = request.form["variable"]
return render_template(
"result.html",
result=result)
When I run the local environment, and type in a ticker symbol, the next URL is:
webapp.com/result/variable
I'm assuming it's HTML that I need to edit? I've read the quickstart documentation for Flask which isn't making sense to me and looked up similar questions but I can't seem to find an answer to this.
You are coming at it from the wrong way. When Jinja creates index.html based on your template you can't know what variable is going to be, so how is Jinja supposed to know?
What you need to do is send the form back to the same route and then redirect the user to whatever they typed in. So something like this:
from flask import request, redirect, url_for
#app.route("/", methods=['GET', 'POST'])
def markert_hours_today():
if request.method == 'POST':
result = request.form['variable']
return redirect(url_for('ticker_result', variable=result)
return render_template("index.html")
Edit: forgot to rename variable from user_input to result.
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>
This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 3 years ago.
I'm creating a web app in Python/Flask to display tweets using twitters API using tweepy. I have set up an HTML form, and have got the script that finds the tweets with a certain input, currently, this is hard coded. I want the users to input a hashtag or similar, and then on submit, the script to run, with that as its parameter
I've created a form, with method GET and action is to run the script.
<form class="userinput" method="GET" action="Tweepy.py">
<input type="text" placeholder="Search..">
<button type="submit"></button>
</form>
I dont know how I would get the users input and store it in a variable to use for the tweepy code, any help would be greatly appreciated
templates/index.html
<form method="POST">
<input name="variable">
<input type="submit">
</form>
app.py
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['POST'])
def my_form_post():
variable = request.form['variable']
return variable
I guess you have set up and endpoint to run that script, an URL mapped to a function. In that case you need to call it from the form action.
for example
#app.route('/my-function')
def your_function(parameters):
"code to do something awesome"
return "the result of your function"
So, in your form you should:
<form class="userinput" method="GET" action="/my-function">
<input type="text" placeholder="Search..">
<button type="submit"></button>
</form>
That should do the trick.
Go to the Flask home page for more examples.
This question already has answers here:
Reload Flask app when template file changes
(13 answers)
Closed 4 years ago.
I have a page with a simple text and a button in a form
<html>
<head>
</head>
<body>
<h1>JASON</h1>
<form>
<button type="submit" formmethod="POST">Activate</button>
<br>
<input type="hidden" value="act.12344" name="sub" />
</form>
</body>
</html>
And this python script
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
#app.route('/atdt', methods=['GET', 'POST'])
def atdt():
if request.method == 'POST':
print('post')
requested = request.form['sub']
ver = str(requested).split('.')
if ver[0] == 'act':
print('act')
modif(ver[1]) #this func modifies the index page
return render_template('index.html')
else:
return render_template('index.html')
The point of the script is to change the name jason in something else...and it works well, the page is changed and its all good
But my flask program wont show it...the '.html' page its changed, and if I open it manually, outside the program it works!
But if i give python the line return render_template('index.html') but it wont render it
If i try to refresh manually it will just show me the old page
Any help ?
You are not modifying the html, You are just calling a function that returns modified version of an input!
First of all you have to use tempalte engine
Your HTML Should be something like this:
<html>
<head>
</head>
<body>
<h1>{{name}}</h1>
<form>
<button type="submit" formmethod="POST">Activate</button>
<br>
<input type="hidden" value="act.12344" name="sub" />
</form>
</body>
</html>
And your view should look like this:
#app.route('/atdt', methods=['GET', 'POST'])
def atdt():
if request.method == 'POST':
print('post')
requested = request.form['sub']
ver = str(requested).split('.')
if ver[0] == 'act':
print('act')
name = modif(ver[1]) #this func modifies the index page
return render_template('index.html', name=name)
else:
return render_template('index.html', name="JASON")
The template engine will handle The name change
Flask uses Jinja2 Template Engine, You can read more about it here
So I am trying to make a form that accepts text when submitted and returns submitted text using the /process function.
Here is my code for index.html:
<!DOCTYPE>
<html>
<head>
<title>Whats my name</title>
<h1>What's my name?</h1>
</head>
<body>
<input type="text">
<form action="POST"
>
<p>your name</p><input type="submit">
</body>
</html>
And here is my Python code:
from flask import Flask, render_template,redirect # Import Flask to allow us to create our app, and import
# render_template to allow us to render index.html.
app = Flask(__name__) # Global variable __name__ tells Flask whether or not we
# are running the file directly or importing it as a module.
#app.route('/')
def home():
return render_template('index.html')
#app.route('/process',methods=['POST'])
def input():
return redirect ('/')
app.run(debug=True)
To retrieve the name value from your html you'll have to add a tag name to the input.
Please see example below, here I named it user_name:
<html>
{...}
<body>
<form action="" method="post">
<input type="text" name="user_name"/>
<p>your name</p>
<input type="submit"/>
</form>
</body>
</html>
Then request the value in your backend Python code
# import the needed request module from Flask
from flask import request
(...)
#app.route('/process', methods=['POST'])
def input():
name = request.form['user_name']
return name
Check this out first: https://www.w3schools.com/tags/att_form_action.asp
Action should be "/process" instead of "POST".
Method is "POST". Also you will need input elements in the form to allow user inputs something.
The input value can be retrieved on the flask side by request.form['value of name attribute of input']
https://www.w3schools.com/tags/tag_input.asp
I would like to recommend you to use https://flask-wtf.readthedocs.io/en/stable/ flask wtf to generate form and retrieve users' input.