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
Related
I am trying to send a form to a python server using flask as the framework, however the methods variable keeps giving me an error that no such variable exists. I have tried googling it but haven't found anything online.
from flask import Flask, request
#app.route('/form', methods=['GET', 'POST'])
def form():
# allow for both POST AND GET
if request.method == 'POST':
language = request.form.get('language')
framework = request.form.get('framework')
return '''
<h1>The language value is: {}</h1>
<h1>The framework value is: {}</h1>'''.format(language, framework)
# otherwise handle the get request
return '''
<form method="POST">
<div><label>Language: <input type="text" name="language"></label></div>
<div><label>Framework: <input type="text" name="framework"></label></div>
<input type="submit" value="Submit">
</form>'
'''
from flask import Flask, request
app = Flask(__name__)
#app.route('/form', methods=['GET', 'POST'])
def form():
# allow for both POST AND GET
if request.method == 'POST':
language = request.form.get('language')
framework = request.form.get('framework')
return '''
<h1>The language value is: {}</h1>
<h1>The framework value is: {}</h1>'''.format(language, framework)
# otherwise handle the get request
return '''
<form method="POST">
<div><label>Language: <input type="text" name="language"></label></div>
<div><label>Framework: <input type="text" name="framework"></label></div>
<input type="submit" value="Submit">
</form>'
'''
if __name__ == '__main__':
app.run(debug=True)
by adding these two code blocks in the code as shown in the above code, the app is working perfectly fine.
app = Flask(__name__)
if __name__=='__main__':
app.run(debug=True)
Thanks in Advance!!
I did the following things to create a login or Sign in the form:-
1)Created secret key
2)Used LoginManager and passed the app
3)Created a route for login.html
I am getting a Method Not Allowed page when I access the login page on the localhost.
Here is the code:-
app.py
```
from flask import Flask, render_template, request, flash, redirect, url_for, session, logging
from flask_login import LoginManager
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password#localhost/learning'
db = SQLAlchemy(app)
# LoginManager
login_manager = LoginManager(app)# Login Form class
#app.route('/login', methods=['GET,''POST'])
def login():
if request.method == 'POST':
# get form fields
username = request.form['username']
password_candidate = request.form['password']
# getting user
login_user = Flask_Users.query.filter_by(username).first()
if login_user > 0:
# Get stored hash
password = login_user.password # is this right way to get one field from login_user??
# Compare passwords
if sha256_crypt.verify(password_candidate, password):
app.logger.info('PASSWORD MATCHED')
else:
app.logger.info('NO user')
return render_template('login.html')```
login.html
```
{% extends 'layout.html' %}
{% block body %}
<h1>Login</h1>
{% include 'includes/_messages.html' %}
<form action="" method="POST">
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" value={{request.form.username}}>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" value={{request.form.password}}>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}
I followed what was in the documentation page. In the console, I am getting code 405 and error is the pic[enter image description here][1]
[1]: https://i.stack.imgur.com/fkf0m.png
Any help is appreciated. I did go through relevant posts on the website as well, but could not find anything relatable
You have a typo in your code
methods=['GET,''POST']
You need to correct to
methods=['GET','POST']
I keep getting the following error:
BadRequestKeyError: 400 Bad Request: KeyError: 'customer_account_number'
Where am I going wrong? I am using Python 2.7 running Flask.
Here is my python script:
import os
from flask import Flask, render_template, request
template_dir = os.path.abspath('c:/users/ned06')
app = Flask(__name__, template_folder=template_dir)
#app.route('/')
def quiz():
return render_template('test.html')
#app.route('/account_number', methods=['POST'])
def quiz_answers():
customer_account_number = request.form["customer_account_number"]
if __name__ == "__main__":
app.run(debug=True)
and here is my HTML:
<form action="/account_number" method="POST">
<p>Input Customer Account Number</p>
<input name="customer_account_number" </input>
<input type="submit" value="Submit" />
</form>
<input name="customer_account_number" </input>
YOu are missing closing bracket here.
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.
Using the following:
from flask import Flask, render_template
import beautiful_soup_tidal
app = Flask(__name__)
#app.route('/')
def form():
return render_template('form_submit.html')
#app.route('/richmond', methods=['POST'])
def richmond():
someTides = beautiful_soup_tidal.getTides()
return render_template('richmond.html',someTides=someTides)
if __name__ == "__main__":
app.run(debug=True)
And attempting to render the following (richmond.html):
<div id="content" class="form-group">
<form method="post" action="/richmond">
<label style="vertical-align: middle;">channel depth at mean low water
<input type="number" step="0.1" value = "34.5" name="channelDepth"/>FEET</label><br><br>
<label style="vertical-align: middle;">required underkeel clearance
<input type="number" step="0.1" value = "2" name="underkeelClearance"/>FEET</label><br><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
I get the following error: 'The method is not allowed for the requested URL.'
If I delete ', methods=['POST']' in the first section the template renders.
The question: How do I render the template successfully using the post method?
i believe this line should also include GET so that you can render the html form first time round before you actually click submit to post it.
#app.route('/richmond', methods=['POST'])
so it would change to
#app.route('/richmond', methods=['GET', 'POST'])