I am trying to pass an input variable in a form tag to use in a python function. However, I keep getting different HTTP errors. I have changed the code numerous times drawing reference from other questions on the stack, none of them have worked.
The problem seems to be with the URL, the input variable appears in the URL but I may not be handling it correctly. I'm also getting an error sometimes with the 'attempted_question' not being recognized.
Any help appreciated
index.html
<html>
<head></head>
<body class = "body">
<body>
<form action="{{ url_for('about') }}" method=”PUT”>
<label> Enter population based question: </label>
<input name = "pop_question" >
<button type=”submit”> Submit </button>
</form>
<p> </p>
</body>
</body>
</html>
pass.html
<html>
<head></head>
<body class = "body">
<body>
<p> i am here {{ attempted_question }}</p>
</body>
</body>
</html>
</html>
run.py
from flask import Flask, render_template
#app.route("/")
def hello():
return render_template("index.html")
#app.route("/about", methods=['GET'])
def about():
living = request.form['pop_question']
return render_template('pass.html', attempted_question=living )
if __name__ == "__main__":
app.run(debug=True)
You use different http methods when sending and receiving data.
Try to use same method. 'POST' for example.
index.html
...
<form action="{{ url_for('about') }}" method=”POST”>
...
run.py
...
#app.route("/about", methods=['POST'])
...
Related
This question already has answers here:
How to debug a Flask app
(14 answers)
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 4 years ago.
So, what I want to do is read 2 csv files, send them over my app.py and then print the results in a new HTML using Flask. Problem is, I can't find what I'm doing wrong. To be more specific I'm sending my CSV files through my app.py and I get either internal errors (500) or server errors (404) one after the other and I don't have a syntax error so it MUST be logical. So, what can I do to fix that because I'm at square one and my gut says that is as trivial as they come.
app.py:
from flask import Flask, render_template, request
import numpy
import pandas
import jinja2
app = Flask(__name__)
#Create a route to a file which is called "/" and uses both GET and POST
#app.route('/', methods=['GET', 'POST'])
#define function send
def results():
#retrieve data from form where we used POST
if request.method == 'POST':
table1=request.files['table1']
table2=request.files['table2']
#define function
def new_t(t1,t2):
#Combine t1 and t2
t3=np.hstack((t1,t2))
return(t3)
results=new_t(t1,t2)
#sends input to the template results.html with the inherited value "results"
return render_template('/results.html', results=results)
#in case there was a mistake we are redirecting the user to index.html
return render_template('/index.html')
index.html:
<!DOCTYPE html>
<html>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<body>
<h1>Give to your CSVs: </h1>
<!-- Create a form that sends data to our server (in this case local) using POST method -->
<form method="POST" action="/results" enctype="multipart/form-data" >
<!-- Style our input using Bootstrap CSS -->
<div class="form-group">
<!-- Create an input with type text so we can type our age in text form -->
<b>Choose Table1 (CSV format):</b>
<input type="file" name="table1">
<b>Choose Table2 (CSV format):</b>
<input type="file" name="table2">
</div>
<!-- Create and style our submit button-->
<input class="btn btn-primary" type="submit" value="submit">
</form>
</body>
</html>
results.html
<!DOCTYPE html>
<html>
<header>
</header>
<body>
<!-- Print out the age that we typed which was sent from our app.py -->
<h1>Results: </h1>
<table>
{{ results|safe }}
</table>
</body>
</html>
I have a Python script that uses Flask web framework to let users ask a question and depending on some certain questions, the application should ask back some questions to the user on a second webpage. The answers to the questions are evaluated based on the questions and displayed on the initial webpage.
model.py
### Importing Flask ###
from flask import Flask, render_template, request, session, redirect, url_for
### Initializing Flask ###
app = Flask(__name__)
#app.route('/')
def index():
return render_template('init.html')
#app.route('/handle_data', methods = ['POST', 'GET'])
def handle_data():
### User Inputs Question ###
userQuestion = request.form['userQuestion']
def model():
message = "Depends on User"
if message == "Depends on User":
return render_template('user_information.html', userQuestion = userQuestion)
else:
message = "Your answer is ABC."
return message
message = model()
return render_template('init.html', userQuestion = userQuestion, message = message)
#app.route('/user_information', methods = ['POST', 'GET'])
def user_information():
userLevel = request.form['userLevel']
userDOJ = request.form['userDOJ']
userType = request.form['userType']
message = "Answer for Eligibility."
return render_template('init.html', userLevel = userLevel, userDOJ = userDOJ, userType = userType, message = message)
if __name__ == '__main__':
app.run()
These are my two HTML files:
init.html (initial webpage)
<!DOCTYPE html>
<html>
<head>
<title>Human Resources</title>
<!-- for-mobile-apps -->
</head>
<body>
<div class="main">
<div class="w3_agile_main_grid">
<h2>Human Resource Portal</h2>
<br>
<p>Hi</p>
<form action="{{ url_for('handle_data') }}" method="post" class="agile_form">
<input type="text" name="userQuestion" placeholder="Ask your question..." required="">
<input type="submit" value="Submit">
</form>
<p>{{ message }}</p>
</div>
</div>
</body>
</html>
user_information.html (second webpage)
<!DOCTYPE html>
<html>
<head>
<title>Human Resources</title>
</head>
<body>
<div class="main">
<div class="w3_agile_main_grid">
<h2>Human Resource Portal</h2>
<form action="{{ url_for('user_information') }}" method="post" class="agile_form">
<!--<input type="text" name="userName" placeholder="Enter your name." required="">-->
<input type="text" name="userLevel" placeholder="What is your level?" required="">
<input type="text" name="userDOJ" placeholder="What is your date of joining?" required="">
<input type="text" name="userType" placeholder="Are you on sabbatical or specialist?" required="">
<input type="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
When I execute my script and enters a question, what I get is the HTML code for user_information.html as my answer which is not what I want.
Ouput after I click Submit:
https://ibb.co/cwhRpk
Expected output after I click Submit:
https://ibb.co/c7CFh5
https://ibb.co/dX9T25
I can get the desired output if I remove the model() construct but that will make my code inefficient because in my actual application I have to call model() multiple times with different parameters.
Can anyone please suggest me what approach should I take? I'm totally stuck in this part. Thanks, any help is appreciated!
Your nested model() function does not make any sense at all. It returns the result of render_template, which is a complete response including HTTP headers etc. If you try and insert that into another template, Jinja will be forced to try and convert it to a string, which gives the result you see.
This is not at all the way to compose templates. Jinja supports template inheritance; you should call render_template once only, using a child template that inherits from a common base.
I have 2 functions in a single direction of page.
How to access both of them individually?
Now what's happening is, only 1st function is getting called.
The below program is a madeup prototype and my requirement builds on this logic.
from bottle import get,post,run,route,request
content1 = '''
<html>
<h1>Page 1 function </h1>
<form action='details' method='post'>
<input type = "text" name="uname">
<input type = "submit" >
</form>
</html>'''
content11 = '''
<html>
<h1>Page 2 function </h1>
<form action='details' method='post'>
<input type = "text" name="uname">
<input type = "submit" >
</form>
</html>'''
content2 = '''<html><h1>Hello %s </h1></html>'''
#get('/home')
def page1():
return content1
def page2():
return content11
#post('/details')
def page3():
u_name = str(request.forms.get('uname'))
return content2 %u_name
run(host='localhost', port=8080, debug=True)
The way you are asking the question implies you want to provide two separate web pages from the same address. REST doesn't work this way.
You need to provide a second route to access the code in page2()
Ok so I am new to flask, and want to know what objects or tools I would use to do this. I want to create a form, where the user inputs some text, clicks a submit button, then the text that they submitted is bound as a python string, and has a function run on it, and that text is then posted back onto the web page they are viewing with the return value of that function it went through. Here is an example:
html form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action = "/" method="get">
<input type="text" name="mail" size="25">
<input type="submit" value="Submit">
</form>
<textarea cols="50" rows="4" name="result"></textarea>
</body>
</html>
Then here is what I believe should be the url function should look like
#app.route('/', methods=['GET', 'POST'])
def form():
if request.method == 'GET':
input_text = request.data #step to bind form text to python string
new_text = textfunction(input_text) #running the function on the retrieved test.
return (new_text) # no idea if this is write, but returns text after modification.
What would be the best way to set this up? Would it be correct to put a variable as the value for the input html? Need some help on this.
Basically, what you want to do is have a block in your template that is only included if the variable has a value set. See the following example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action = "/" method="get">
<input type="text" name="mail" size="25">
<input type="submit" value="Submit">
</form>
{% if result %}
<textarea cols="50" rows="4" name="result">{{ result }}</textarea>
{% endif %}
</body>
</html>
and then in your python code
#app.route('/', methods=['GET', 'POST'])
def index(result=None):
if request.args.get('mail', None):
result = process_text(request.args['mail'])
return render_template('index.html', result=result)
def process_text(text):
return "FOO" + text
I am completely new to python and Flask and I am trying to run in my computer the code showed in this page:
http://runnable.com/UhLMQLffO1YSAADK/handle-a-post-request-in-flask-for-python
This are the steeps I follow and the code:
1-I have installed Flask
2-Files
File app.py
# We need to import request to access the details of the POST request
# and render_template, to render our templates (form and response)
# we'll use url_for to get some URLs for the app on the templates
from flask import Flask, render_template, request, url_for
# Initialize the Flask application
app = Flask(__name__)
# Define a route for the default URL, which loads the form
#app.route('/')
def form():
return render_template('form_submit.html')
# Define a route for the action of the form, for example '/hello/'
# We are also defining which type of requests this route is
# accepting: POST requests in this case
#app.route('/hello/', methods=['POST'])
def hello():
name=request.form['yourname']
email=request.form['youremail']
return render_template('form_action.html', name=name, email=email)
# Run the app :)
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=int("80")
)
File form_action.html
<html>
<head>
<title>Handle POST requests with Flask</title>
<link rel=stylesheet type=text/css href="style.css">
</head>
<body>
<div id="container">
<div class="title">
<h1>POST request with Flask</h1>
</div>
<div id="content">
Hello <strong>{{name}}</strong> ({{email}})!
</div>
</div>
</div>
</body>
</html>
File form_submit.html
<html>
<head>
<title>Handle POST requests with Flask</title>
<link rel=stylesheet type=text/css href="style.css">
</head>
<body>
<div id="container">
<div class="title">
<h1>POST request with Flask</h1>
</div>
<div id="content">
<form method="post" action="{{ url_for('hello') }}">
<label for="yourname">Please enter your name:</label>
<input type="text" name="yourname" /><br />
<label for="youremail">Please enter your email:</label>
<input type="text" name="youremail" /><br />
<input type="submit" value="Send" />
</form>
</div>
</div>
</div>
</body>
</html>
3-I run the py file:
sudo python app.py
[sudo] password for jose:
* Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
When I open the browser I write:
file:///home/jose/Escritorio/python/app/form_submit.html
I insert the data in the 2 forms and I press Send and this is what happens:
URL: file:///home/jose/Escritorio/python/app/{{url_for('hello')}}
Web Page: File not found
What am I doing wrong?
0.0.0.0 means that you can access the flask website from outside of the website host. Use the host ip plus the port # you specified
http://:80/hello in your case. That should display the form_action.html you specified in your routes.
If you want save form data, your code didn't work. You must have a database or save in a file.