I'm trying to run a simple Flask application based on multiple simple tutorials. My goal is to finish a full tutorial and manipulate the code to build a search web app that connects to a SQL server database.
However, when I try running the code and provide an integer input, the POST method is not working, so it will not return a {{value}} as specified.
I've tried adding and removing several components: adding in the action='/' on the HTML, and trying to run the code as well without it. That didn't make a difference.
I have methods=['GET', 'POST'] already.
I even tried {{ url_for('/') }} and that just gave me an Internal Server Error.
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
#app.route('/hello')
def hello():
return "My flask app"
#app.route('/', methods=["GET", "POST"])
def home():
if request.method == "POST":
value = int(request.form["number"])
add_one = value + 1
return render_template('index.html', string="WORLD!", value=add_one)
return render_template('index.html', string="WORLD!")
if __name__ == "__main__":
app.run()
HTML:
<body>
<div class="container">
<h1>Hello, {{string}}</h1>
<br>
<form action='/' role="form" method="post" onsubmit="return false;">
<div class="form-group">
<input type="number" class="form-control" name="number" placeholder="Enter a number" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<p>The calculated number is {{value}}</p>
<br>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</body>
While running the code my app renders successfully, but when submitting a number the server does not register the input.
I don't even receive an error. All I see in the terminal is "GET / HTTP/1.1" 200.
By removing onsubmit="return false;" attribute of the form in the HTML.
And by restarting your app and reload the HTML.
It should be working.
Related
My flask template is not displaying properly. For some reason, the templating language is being displayed on the webpage.
Here is what it looks like (red circles indicate items that should not be on the web page)
I am not sure why this is happening. The templates are stored in a folder called static and in my app.py, I have the following line as well:
app = Flask(__name__, template_folder='static')
Edit: Here is the code that renders the following portion of this page:
`
{% if passphrase %}
<div>
<h4>Information</h4>
<p>Address: 123_easy_uncover_street</p>
</div>
{% else %}
<div class="col">
<h4>Enter passphrase</h4>
<form action="" method="POST" style="text-align:left">
<label for="passphrase">Passphrase</label>
<input type="text" id="passphrase" name="passphrase">
<br>
<input type="submit" value="Submit">
</form>
</div>
<div id="status" class="col" >
<p><i>Please enter your passphrase</i></p>
</div>
{% endif %}
</div>`
Flask code:
from app.bank_database import BankDatabase
from flask import Flask, request, render_template
import random
import json
app = Flask(__name__, template_folder='static')
db = BankDatabase()
#app.route('/', methods=['GET', 'POST'])
#app.route('/index.html', methods=['GET', 'POST'])
def index():
return render_template("index.html", passphrase="")
#app.route('/check_passphrase', methods=['GET', 'POST'])
def check_passphrase():
passphrase = request.args.get("passphrase")
if db.check_passphrase(passphrase):
#Show address here
#TODO - change view to show passphrase
return render_template("index.html", passphrase=passphrase)
return render_template("index.html", passphrase="")
app.run(debug=True,host="0.0.0.0")
I am trying to deploy my ml model in flask. The error appear when i am trying access my height-weight.html page from the home.html page.
code for app.py
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
if __name__ == "__main__":
app.run()
This works perfectly fine. It render home.html. No problem here.
Output 1:-
But as soon as I click Check Project button following error occurs.
Output 2:-
Code for height-weight.py
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))
#app.route('/predict')
def weight_predict():
return render_template('height-weight.html')
#app.route('/predict',methods=['POST'])
def predict():
if request.method == 'POST':
height = float(request.form['height'])
gender = float(request.form['gender'])
prediction = model.predict([[gender, height]])
output = round(prediction[0], 2)
return render_template('height-weight.html', weights = output)
if __name__ == "__main__":
app.run()
And finally my html code for height-weight.html look like this.
Code:-
<section id='form'>
<div class="container">
<h1>Height Weight Prediction</h1>
<form action="{{ url_for('predict')}}" method="get">
<div class="card">
<div class="card-body">
<label>Gender</label>
<input type="text" class="form-control" id='gender' placeholder="Input Your Gender" required="required">
</div>
<div class="card-body">
<label>Height</label>
<input type="text" class="form-control" id='height' placeholder="Input Your Height" required="required">
<small class="form-text text-muted">Please input your height in 'Inch'.</small>
</div>
<button type="submit">Predict Weight</button>
</div>
</form>
{{ weights }}
</div>
</section>
My expected output is to show height-weight.html pages from where i can predict the weight. This is my error. Hope you guys understand my error and please help me. Thanks in advance.
You are redirecting the page to 127.0.0.1:5000/height-weight.html which is looking for the HTML file on the backend server. You need to redirect the page to /redirect by providing it in an anchor tag.
Flask renders the HTML page and returns the response it doesn't serve the HTML page directly. That's why you are getting 404 error.
Hope this helps!
I am new to web development. I am trying to create a web page which will display index from elastic search database. I am using python flask for backend.
I see html page and python console shows index.
But I am not able to fetch index from HTML page.
I am not sure what could be the issue
Python code is as follows:
from flask import Flask,render_template, request
from elasticsearch import Elasticsearch
app = Flask(__name__)
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
doc1 = {"food": "Japanese", "spice_level": "moderate"}
doc2 = {"food": "Italian", "spice_level": "mild"}
doc3 = {"food": "Indian", "spice_level": "spicy"}
es.index(index="food", doc_type="spice_level", id=1, body=doc2)
resp = es.get(index="food", doc_type="spice_level", id=1)
print(resp)
#app.route('/')
def home():
return render_template('index.html')
app.route('/dashboard', methods=['GET', 'POST'])
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
HTML code is as follows:
<!DOCTYPE html>
<BODY bgcolor="cyan">
<form method="GET" action="/dashboard">
<center>
<H1>Database UI </H1> <br>
search here <input type = "text" name= "index" /> <br>
<input type = "submit">
</center>
</form>
</BODY>
</html>
Whenever I type a index name and click on search button, page gives me error as :
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I cannot see any other error then this, and it's really difficult to debug with less information about error.
why your /dashboard return 404 ?
because lack of view function to response.
app.route('/dashboard', methods=['GET', 'POST']) is invalid.
How to access /dashboard of elascticsearch ?
In your case, the simplest way is modify the index.html
<!DOCTYPE html>
<BODY bgcolor="cyan">
<form method="POST" action="http://localhost:9200/dashboard">
<center>
<H1>Database UI </H1> <br>
search here <input type = "text" name= "index" /> <br>
<input type = "submit">
</center>
</form>
</BODY>
</html>
can you use this here? for Parse data from html to python code you need to have POST inside #app.route like this:
#app.route("/", methods=['GET', 'POST'])
def home():
return render_template('index.html')
if you want to pase data into index.html you can use this here:
somedata = "variable string"
render_template('index.html', somedata=somedata)
inside index.html do {{ somedata }}
<!DOCTYPE html>
<BODY bgcolor="cyan">
<form method="POST" action="">
<center>
<H1>Database UI </H1> <br>
<!-- it will show (variable string) -->
{{ somedata }}
search here <input type = "text" name= "index" /> <br>
<input type = "submit">
</center>
</form>
</BODY>
</html>
happy codeing.
This question already has answers here:
Flask - POST Error 405 Method Not Allowed
(3 answers)
Closed 3 years ago.
I am attempting to create a basic login page on a raspberry pi, but when I try to login to the page I keep getting a 405 error. I have researched the issue but it seems to only appear if you aren't using the correct methods, but since it's a login screen POST and GET should be more than sufficient.
Python
from flask import Flask
from flask import Flask, flash, redirect, render_template, request, session, abort
import os
app = Flask(__name__)
#app.route('/')
def home():
if not session.get('logged_in'):
return render_template('login.html')
else:
return "Hello Boss!"
#app.route('/login', methods=['POST', 'GET'])
def do_admin_login():
if request.form['psw'] == 'password' and request.form['id'] == 'admin':
print ("Hey ya!")
else:
print('wrong password!')
return home()
if __name__ == "__main__":
app.secret_key = os.urandom(12)
app.run(debug=True,host='0.0.0.0', port=80)
HTML
<!DOCTYPE html>
<html>
<body>
<h1>Please login</h1
<form method="POST">
<input name="id" type="text" placeholder="Enter UserID">
<br>
<input name="psw" type="password" placeholder="Enter Password">
<input type="submit">
</form>
</body>
</html>
I have been redirected to a different question which resolves it through changing the action part of the however mine does not have action so this should not be the same issue. I have attempted adding an action element to it but that has not changed anything
The problem is that you need to specify the action attribute in HTML:
<form method="POST" action="{{url_for('do_admin_login')}}">
<input name="id" type="text" placeholder="Enter UserID">
<br>
<input name="psw" type="password" placeholder="Enter Password">
<input type="submit">
</form>
As you may notice that I used url_for function to generate a URL to the given endpoint with the method provided ( do_admin_login() in this case ). So it is worth to mention that you need to change your statement return home() to return url_for("home").
I tried this approach to pass the form input variable to function via url_for method. But its not working. can anyone check and let me know whats wrong in this code.
Function:
#app.route('/report_data/<year>/<week>', methods = ['POST'])
def report_data(year,week):
print year
print woy
HTML Code :
<html>
<body>
<form action="{{ url_for('report_data', year=n_year, week=n_woy) }}" method="post">
<h3> Enter the details </h3>
Year :
<input type="text" name="n_year"> <br>
<br>
Week :
<input type="text" name="n_woy"> <br>
<br>
<input type="submit" value="Submit"> <br>
</form>
</body>
</html>
Issue:
Getting "None" for both variable.
Firstly, How do you provide year, week values before submitting them in your HTML code ?
Did you render the HTML template in your function? If not, how does your flask function knows that you were seeking from that specific form?
If this is your Flask app code -
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/report_data', methods = ['POST', 'GET'])
def report_data():
if request.method == 'POST':
result = request.form
query_year = result['n_year'].encode('ascii', 'ignore')
query_week = result['n_woy'].encode('ascii', 'ignore')
print(query_year, query_week)
return render_template('so_test.html')
if __name__ == '__main__':
app.run(debug=True)
And opened the URL -
http://127.0.0.1:5000/report_data
And I get this picture.
Once I post the data, I can see this data in my Flask app console.
('2018','08')