How to send data from flask to html template

21,613

Problem

Your function samplefunction() always renders new.html without a variable included because of the initial return statement.

def samplefunction():
    return render_template('new.html')

Fix

You need to add if request.method == 'GET': and if request.method == 'POST':, and then your code will work. And change the variable name as the other answer by @Harrison suggests: bot = random.choice(greetOut) not bot = random.choice(greetout)

Updated Code

def samplefunction():
    if request.method == 'GET':
        return render_template('new.html')
    if request.method == 'POST':
        greetIn = ['hey', 'hi', 'hey there', 'hi there', 'hello', 'hola', 'yoo']
        byeIn = ['bye', 'see you later', 'catch you later', 'toodles']
        nameOut = ['my name is Fatty!!', 'Fatty is my name', 'you can call me Fatty', 'I go by the name of Fatty']
        greetOut = ['hey there!', 'hi!', 'hi there!', 'hey!']
        byeOut = ['bye bye', 'bye. see you later']
        human1 = request.form['human']
        if human1 in greetIn:
            bot = random.choice(greetOut)
            return render_template('new.html', bot=bot)
        else:
            render_template('new.html')

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080, debug=True)
Share:
21,613
Anupama_K
Author by

Anupama_K

Updated on July 25, 2020

Comments

  • Anupama_K
    Anupama_K over 3 years

    I have a small application where input is taken from the user and based on it data is displayed back on the html. I have to send data from flask to display on html but unable to find a way to do it. There's no error that I encountered.

    [UPDATED]: Python script :

        from flask import Flask, render_template, request
        import random
    
        app = Flask(__name__, template_folder='templates')
    
        @app.route('/', methods=['GET','POST'])
        def samplefunction():
            if request.method == 'GET':
                return render_template('new.html')
            if request.mthod == 'POST':
                greetIn = ['hey', 'hi', 'hey there', 'hi there', 'hello', 'hola', 'yoo']
                byeIn = ['bye', 'see you later', 'catch you later', 'toodles']
                nameOut = ['my name is Fatty!!', 'Fatty is my name', 'you can call me Fatty', 'I go by the name of Fatty']
                greetOut = ['hey there!', 'hi!', 'hi there!', 'hey!']
                byeOut = ['bye bye', 'bye. see you later']
    
                human1 = request.form['human']
    
                if human1 in greetIn:
                    bot = random.choice(greetOut)
                    return render_template('new.html', bot=bot)
                else:
                    bot = 'Sorry..no idea!!!'
                    return render_template('new.html', bot=bot)
    
      if __name__ == "__main__":
         app.run(debug=True)
    

    HTML code :

    <html>
      <head>
        <title>BOT</title>
        <script>
            var bot = {{ bot }}
        </script>
      </head>
      <body>
          <h1>Hello, type something to begin!</h1>
          <form method='post'>
            Human: <input type='text' name='human'><br>
            Bot: {{ bot }}<br>
            <input type="submit" name="action">
          </form>
      </body>
    </html>
    

    Any help would be appreciated.

    Thank You!

  • Anupama_K
    Anupama_K almost 7 years
    Did this but it's still not working. The page just refreshes on button click and nothing appears in place of {{bot}}
  • Anupama_K
    Anupama_K almost 7 years
    It's still not working...simply rendering new.html without the variable everytime button is clicked
  • David John Coleman II
    David John Coleman II almost 7 years
    Then you haven't copied correctly, because your code does work, I'm getting the expected results. Are you sure that you have copied exactly the code? After @app.route('/', methods=['GET','POST']) The definition of def samplefunction() needs to be exactly as I have written above, and your code does do what you want. The bot response is written to your html page in the place of the variable {{ bot }} in the line: Bot: {{ bot }}<br>.
  • David John Coleman II
    David John Coleman II almost 7 years
    You do know that you need to input text into the human text box and that the input needs to match one of the strings from: greetIn list, right? I assumed you would know that since it's your code. You cannot input monkey brain and expect to get a robot answer... Also, The if __name__ == "__main__": statement is dependent on your environment, and that should be configured as you wish. I assume you know that since you have at least been able to render the new.html page without the bot response.... Please give me an update or post your error messages, and I'll help you figure it out.
  • Anupama_K
    Anupama_K almost 7 years
    Following is the structure of my folder: /bot --- /new1.py /templates -- new.html I have copied your code correctly and made a single change in if __name__ == "__main__": app.run(debug=True) and then in cmd after going to the /bot folder I run the following commands: set FLASK_APP=new1.py and flask run I am not getting any error message or anything, the page just reloads after button click without the variable.
  • David John Coleman II
    David John Coleman II almost 7 years
    You stated, "the page just reloads after button click without the variable". And above you stated, "still not working...simply rendering new.html without the variable everytime button is clicked "... Did you input text into the Human: text box? You need to input one string of text from this variable: greetIn = ['hey', 'hi', 'hey there', 'hi there', 'hello', 'hola', 'yoo'] such as hey or hi exactly in order to receive a bot response. You may also run your app with the command $ python new1.py or $ python3 new1.py but both your solution and this noted one work fine.
  • Anupama_K
    Anupama_K almost 7 years
    I am giving the input in the textbox and then clicking the button...and have also tried to run my app with python new1.py or python3 new1.py but still it's just rendering the page without any response.
  • David John Coleman II
    David John Coleman II almost 7 years
    I made a demo of your app and if functions fine. In the demo, I display the contents of the files in your app, then run the app with python3, then visit the browser to show how to test your app in the browser. (The port #'s are different because of how I have configured my VM). ** video link here ** Can you visit this link, view the demo, and replicate my demo? If the video is poor quality, you may need to download it, but it should run in google drive.
  • David John Coleman II
    David John Coleman II almost 7 years
    If you cannot replicate the demo, please explain why. Also, explain any errors. Finally, you should update your question above with the new code that you are attempting to use so that your question has good code, and we can determine what is wrong with your environment. Again, copy exactly all the updated code that you are using in your updated question above.
  • Anupama_K
    Anupama_K over 6 years
    The code is exactly the same as the demo you made but there is some problem in the environment because it's still just rendering the html without any change.. I have followed flask documentation to turn this application to a web application.
  • Anupama_K
    Anupama_K over 6 years
    Hey it worked!!! I installed Flask and virtual environment again and then it worked like a charm! Thank You :) :)