I'm trying to make a button in sida2 take me to resultat and post the information named MJ from the input form but I get an error 404 The requested URL was not found on the server and I don't understand why. This is the html part:
<form action="/sida2/resultat.html" method="POST">
<input title="" placeholder="MJ/kq foder" type="text" name="MJ" required>
<br>
<button type="submit">Submit</button>
</form>
And this is the python part:
from flask import Flask, render_template, request
app=Flask(__name__)
#app.route('/')
def home():
return(render_template("hemsida.html"))
#app.route('/sida2/', methods=['POST', 'GET'])
def sida2():
return(render_template("andrasidan.html"))
#app.route('/sida2/resultat', methods=['POST'])
def resultat():
if request.method=='POST':
mj= request.form["MJ"]
return(render_template("resultat.html"))
if __name__ =="__main__":
app.run(debug=True)
I assume it's something obvious I'm missing but I just can't seem to find it.
Use url_for to generate URLs to Flask views. The view you want is resultat.
<form action="{{ url_for('resultat') }}" method="POST">
This will generate the appropriate URL for your resultat() function:
#app.route('/sida2/resultat', methods=['POST'])
def resultat():
The URL you currently have in your form action (/sida2/resultat.html) will not work as your code binds to the URL /sida2/resultat instead.
For a quick overview of the benefits of why you should use url_for over hardcoding your URLs, check out the Flask quickstart section on the topic.
Related
Task:
User types into a form a char e.g. "hello".
this should be send as an post requests to python, because it is later analyzed via a python script
here is my server side code:
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['POST'])
def result():
print(request.form['foo']) # should display 'bar'
return 'Received !' # response to your request.
if __name__ == '__main__':
app.run()
My html code:
<input class="input-text-input" type="text" placeholder="values" name="website">
How can i get the user input from the php form? What would be the best way? The examples in the internet etc. are overloaded. Maybe i have a general mistake.
To make a request from html form to your python flask API, you can do it this way,
HTML FORM
<form action="{{ url_for('addWebsiteUrl') }}" method="post">
<input class="input-text-input" type="text" placeholder="values" name="website">
<input type="submit" value="Submit">
</form>
FLASK API:
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['POST'])
def result():
print(request.form['website']) # should display 'website'
return 'Received !' # response to your request.
if __name__ == '__main__':
app.run()
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 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.
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.
I am trying to use Flask's flash functionality when a user click's a button on a form. The code correctly is identifying the button push as a POST request, yet the webpage yields a 404 error. I have narrowed it down to flash() because without it, there is no 404 error. What is the issue here?
init.py
from flask import Flask, render_template, flash, request
app = Flask(__name__)
#app.route('/', methods=["GET", "POST"])
def meter_input():
print request.method
if request.method == "POST":
print request.form['phone']
flash('test')
return render_template("input.html")
if __name__ == "__main__":
app.run()
input.html
<html>
<form method="post">
<fieldset>
<div class="form-group">
<input id="phone" name="phone" type="text" value="" placeholder="">
</div>
<div class="form-group">
<input type="submit" id="update" value="Update Data"/>
</div>
</fieldset>
</form>
<BR><BR>
</html>
flask.flash apparently uses the flask.session. But the flask.session cannot be used without having defined a secret key for your app. You could have found this out if you started your server in debug mode (which you only should not do in production).
To start your server in debug mode use:
app.run(debug=True)
To fix you actual problem define a secret key right after the creation of the Flask object
app = Flask(__name__)
app.secret_key = "Some secret string here"
I still don't know why you got a 404. You should have gotten a 500 for internal server error