Post values from an HTML form and access them in a Flask view
Your input
doesn't have a name
attribute. That is what the client will pass along to the server. Flask will raise a 400 error if you access a form key that wasn't submitted.
<input name="my_input" id="my_input" type="text" value="{{ email }}">
Sending data from HTML form to a Python script in Flask
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it withurl_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set toget
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.
The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
Passing data from HTML form through Flask to an API
So a good and well documented way to communicate with flask
from html
is via flask wtforms. It helps you essentially to validate your forms in the html and to secure the POST
requests from the frontend usually via a CSRF token.
From the documentation you have a minimal example that could be a good starting point for you:
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class MyForm(FlaskForm):
name = StringField('name', validators=[DataRequired()])
HTML
PS: The curling brackets are from jinja2, a templating language for python.
<form method="POST" action="/">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name(size=20) }}
<input type="submit" value="Go">
</form>
Validating
@app.route('/submit', methods=('GET', 'POST'))
def submit():
form = MyForm()
if form.validate_on_submit():
return redirect('/success')
return render_template('submit.html', form=form)
It is fairly straightforward, you create a form, pass it to the frontend together in the routing and then when the user submits it it tries to validate it.
With all that said, if all you want is to simply send a form data and process that in flask, all you really need to do is create / accept POST requests in your endpoint:
@app.route('/', methods=('GET', 'POST'))
@app.route('home')
def home():
if request.method == 'POST':
form = request.form
value1 = form['value1']
# do something with the values from the form.
return flask.render_template('home.html')
I would not recommend due to validation / security concerns, but it could be a starting point if you are new to flask.
Accessing HTML form data inside Python/Flask
Try stringifying the json data before sending and setting the json header for the call explicitly like this:
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: JSON.stringify(route_object),
contentType: "application/json;charset=utf-8"
success: function (data) {
console.log(data) // display the returned data in the console.
}
});
Getting form data from html form using flask and python
I tried your code and it works for me.
I only had to add global
in cars()
to get results on page /info.json
def cars():
global numCarsEast, numCarsWest, numCarsSouth, numCarsNorth
Use flask to get an image uploaded on a html form
The enctype attribute should be defined within the form tag, not within the input element. Here, the formatting of the data is defined when the form is transmitted.
This could fix the problem.
<form method="post" enctype="multipart/form-data">
<label for="img">Select image:</label>
<input type="file" id="img" name="img" accept="image/*">
<input type="submit" value="submit">
</form>
Related Topics
How Does Python'S Super() Work With Multiple Inheritance
How to Extract Numbers from a String in Python
Pip' Is Not Recognized as an Internal or External Command
Why Does "Pip Install" Inside Python Raise a Syntaxerror
Use Different Python Version With Virtualenv
How to Make a Python Script Standalone Executable to Run Without Any Dependency
Difference Between Modes A, A+, W, W+, and R+ in Built-In Open Function
How to Flush the Output of the Print Function
Running Bash Commands in Python
What's the Difference Between 'Raw_Input()' and 'Input()' in Python 3
How to Force Division to Be Floating Point? Division Keeps Rounding Down to 0
How to Read a Single Character from the User
Accessing Class Variables from a List Comprehension in the Class Definition
Why Isn't the 'Global' Keyword Needed to Access a Global Variable