crisperSkate36
crisperSkate36

Reputation: 25

Flask - How to pass user input from HTML into python script

I am trying to get user input for a 'username' and 'password' from a form in HTML so I can input them into my python script and have the program run. Where do I need to put the request.form to receive both variables?

app.py

from flask import Flask, render_template, url_for, request

app = Flask(__name__)


@app.route('/', methods=['POST', 'GET'])
def home():
    rh = Robinhood()
    rh.login(username="EMAIL", password="PASSWORD")
    projectpath = request.form['projectFilepath']
    return render_template('index.html')

index.html

<form action="{{ url_for('home') }}" method="post">
        <input type="text" name="projectFilepath">
        <input type="submit">
    </form>  

Very new to flask and python, thanks for the help!

Upvotes: 0

Views: 1958

Answers (1)

Yuuty
Yuuty

Reputation: 119

In your html, follow the input type with a placeholder and name; along with an error message that's optional but advised (put outside of the form div); give each method of 'username' and 'password' their request.form values respectively:

<div class="form">
  <form action="" method="post">
    <input type="text" placeholder="Username" name="username" value="{{
      request.form.username }}">
     <input type="password" placeholder="Password" name="password" value="{{
      request.form.password }}">
    <input class="btn btn-default" type="submit" value="Login">
  </form>
  {% if error %}
    <p class="error">Error: {{ error }}
  {% endif %}
</div>

In your python file, put your request.form following an if statement under /login with the methods POST and GET; include your newly made error message:

@app.route('/login', methods=['POST', 'GET'])
def home():
error = None
if request.method == 'POST':
    if request.form['username'] != 'admin' or request.form['password'] != 'admin':
        error = 'Error Message Text'
    else:
        return redirect(url_for('home'))
return render_template('index.html', error=error)

Upvotes: 1

Related Questions