0

When run this program outputs "Get method was called"
Why is it the html code 1. not running 2. returning a get request (the default)
and not returning a post request when the data is entered? The html seems not to be running at all.

This is the part of the HTML file that has the input:

<div>
      <h2>Welcome</h2>
      <form action="{{ url_for('login') }}" method="POST">
        <input type="text" id="user" name="user" placeholder="Please enter username">
        <button>Submit</button>
        </form>
</div> 

This is the part of the .PY file in question:

@app.route('/', methods=['GET', 'POST'])
    def login():
        if request.method == 'GET':
            return "Get method was called"  
        else:  
            user = request.form.get('user')
            return redirect(url_for('home'))
        return render_template("login.html", user = user) 

I am new to python, so I don't know how to beging finding the error.

Capricorn
  • 2,061
  • 5
  • 24
  • 31
Chaim Ochs
  • 129
  • 2
  • 11
  • "HTML" doesn't run (https://stackoverflow.com/questions/145176/is-html-considered-a-programming-language). What does the function `url_for('login')` return? What do you mean by "running" the program, resulting in the output "Get method was called"? Did you just open the html page or submit the form...? – Capricorn Aug 21 '18 at 07:36
  • In order to trigger 'GET' you simply need to navigate to localhost:5000/ (in case port is correct) – bc291 Aug 21 '18 at 07:40
  • Html form fetches only POST requests – bc291 Aug 21 '18 at 07:41

1 Answers1

0

It doesn't work because a route and a function is needed to call the html form. Otherwise, the form never gets called. And a new html file is needed for the second route. The code should read:

from flask import Flask, render_template, request, url_for
app = Flask(__name__, template_folder="./templates")
@app.route('/login')
def login():
    return render_template("login.html")
@app.route('/home', methods=['GET', 'POST'])
def home():
        if request.method == 'GET':
            return "Get method was called"  
        else:  
            user = request.form.get('user')
            return render_template("home.html", user = user)

login.html:

<form action="{{ url_for('home') }}" method="post">
                <input type="text" id="user" name="user" placeholder="Please enter username">
                 <button>Submit</button>
 </form>

home.html:

<h2 style='color:blueviolet;'>User: {{user}}</h2>
Chaim Ochs
  • 129
  • 2
  • 11