简体   繁体   中英

Submitting for python

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM