0

I have my python code where I use html file. Please see below code:

@app.route('/',endpoint='buf')
def index():
    page = """
    <DOCTYPE! html>
    <html lang="en-US">
    <head>
    <title>Hello World Page</title>
    <meta charset=utf-8">
    </head>
    <body>
    <form action="/hello" method="GET">
    First: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>
    <input type="submit" value="Submit">
    </form>
    </body>
    </html>
    """   
    return page


@app.route('/hello',endpoint="new",methods=['GET'])
def login():
         return 'hello %s ' % (request.form['fname'])

This gives me an html page , which has a form with two fields and a submit button. I use virtual env to run this.

Now I want to get the fields first name and last name in my program so that when user click submit I want to display Hello "first name""last name"

Purpose :- to learn how to get the html element values when provided with a code In a python file.

1

1 Answer 1

2

Several things to do to make it work:

  • add POST and GET to supported methods of an app.route:

    @app.route('/', methods=['POST', 'GET'])
    
  • in the view, handle both GET (when the user opens up a web page) and POST (when the user submits the form)

  • extract html code into an html template file and render it in the view (docs on rendering templates)

Here's the code with changes:

from flask import render_template
...

@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        # use request.form['fname'] and request.form['lname'] 
        # to access form input values
    else:
        return render_template('index.html')

Also see documentation page.

Hope that helps.

Sign up to request clarification or add additional context in comments.

16 Comments

and where should my <html></html> code fit in here?
@user3369157 in a separate html file under templates directory (docs).
That what I said, I don't want to use html file. I just wrote my html code in the index() function and I am returning the page. Is there a way to get the input fields from the code I posted?
@user3369157 it is not actually relevant where are you putting that html form code. The answer still briefly explains how you can get the form input values inside the index view.
@user3369157 on the line print request.form['fname'] you should return 'Hello %s %s' % (request.form['fname'], request.form['lname']).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.