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!
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)
Related
Complete newbie to web dev so I suspect this might be more of an architectural problem rather than a technical one..
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
#app.route('/', methods=("POST", "GET"))
def index():
if request.method == 'GET':
return render_template("templ.html")
if request.method == 'POST':
if 'submit' in request.form:
return str([request.form[val] for val in ['input1', 'input2']])
if 'cancel' in request.form:
return redirect(url_for('index'))
app.run(host='0.0.0.0', port='5000')
html:
<!doctype html>
<form action="." method="POST">
<div>
<input type="text" name="input1" required="required">
<input type="text" name="input2" required="required">
</div>
<div>
<button name="submit">Submit</button>
<button name="cancel">Cancel</button>
</div>
</form>
Question: Can I skip 'required' when cancel button is pressed with this simple design or do I need to employ flask_wtf with wtforms.validators? Could I get a working minimal script with my example code please?
There may be a more efficient way of handling it, but this will work as it places the 'Cancel' button in a separate form.
<form action="." method="POST" id ="CancelForm"></form>
<form action="." method="POST">
<div>
<input type="text" name="input1" required="required">
<input type="text" name="input2" required="required">
</div>
<div>
<button name="submit">Submit</button>
<button type="submit" form="CancelForm">Cancel</submit>
</div>
</form>
You may want to give it a different action so you can handle 'cancel' differently
I am trying to create a login page for my flask web app code shown below:
# Route for handling the login page logic
#app.route('/logins', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'GET':
# Just render the initial form, to get input
return (render_template('login.html'))
if request.method == 'POST':
if request.form['username'] == 'admin' or request.form['password'] == 'P#55w0rd':
return redirect(url_for('main'))
else:
error = 'Invalid Credentials. Please try again.'
return render_template('login.html', error=error)
# Set up the main route
#app.route('/main', methods=['GET', 'POST'])
def main():
if request.method == 'GET':
# Just render the initial form, to get input
return(render_template('main.html'))
This is my HTML login page code
<form id="login" action="/logins" method="POST" class="login100-form validate-form">
<span class="login100-form-logo">
<i class="zmdi zmdi-landscape"></i>
</span>
<span class="login100-form-title p-b-34 p-t-27">
Log in
</span>
<div class="wrap-input100 validate-input" data-validate = "Enter username">
<input class="input100" type="text" id="username" name="username" placeholder="Username" value={{request.form.username}}>
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="wrap-input100 validate-input" data-validate="Enter password">
<input class="input100" type="password" id="password" name="pass" placeholder="Password" value="{{
request.form.password }}">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="container-login100-form-btn">
<button type="submit" class="login100-form-btn">
Login
</button>
</div>
</form>
{% if error %}
<p class="error"><strong>Error:</strong> {{ error }}
{% endif %}
but after clicking on login button
404 Method Not allowed
error is coming. what changes to be done in my code so that it can properly redirect to main.html?
Change 'password' to 'pass' :
if request.form['username'] == 'admin' or request.form['pass'] == 'P#55w0rd':
Apologies for my ignorance on the subject. I am just getting my feet wet with Web Dev with Python and Flask.
I am trying to create an app that will take a string from an input field and convert it into a hash and display it on an output page. However, I am not sure if my form is set up correctly.
When I run the application it only returns a false value and displays that the user has not inputted anything even when I type in a random string.
app.py
from flask import Flask, render_template, request, url_for, flash, redirect
from message import MessageForm, validators, ValidationError
from cryptography.fernet import Fernet
app = Flask(__name__)
app.secret_key = 'development'
key = Fernet.generate_key()
f = Fernet(key)
#app.route('/', methods=['GET', 'POST'])
def home():
form = MessageForm(request.form)
if request.method == 'POST' and form.validate_on_submit():
user_message = form.message_field.data
e = user_message.encode(encoding='UTF-8')
token = f.encrypt(e)
output = bytes.decode(token)
return redirect('output.html', output=output)
return render_template('index.html', form=form)
if __name__ == ('__main__'):
app.run(debug=True)
message.py
from wtforms import StringField, SubmitField, validators
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired, ValidationError
class MessageForm(FlaskForm):
message_field = StringField('Please enter the message you would like to
encrypt:', [validators.Required('Please enter a message!')])
submit = SubmitField('Submit')
HTML Form
{% extends 'layout.html' %}
{% block body %}
{{ form.csrf_token }}
<br />
<form action="/" method="POST">
<div class="form-group">
<label style="font-weight: bold;">{{ form.message_field.label }}</label>
<input type="text" class="form-control" name="message" id="message">
<br />
<button type="submit" class="btn btn-primary btn-lg btn-block">Encrypt Message</button>
</div>
</form>
{% for message in form.message_field.errors %}
<div class="alert alert-danger" role="alert">
{{ message }}
</div>
{% endfor %}
{% endblock %}
What I would like is to have the app return back an error if nothing is entered but run the application correctly if something is entered.
I hope that makes sense and as previously stated please excuse my ignorance.
Your help is very much appreciated.
Maybe you could try:
user_message = request.form.get("message")
instead of
user_message = form.message_field.data
In the HTML Form, try to put the csrf_token after the form declaration like this:
<br />
<form action="/" method="POST">
{{ form.csrf_token }}
<div class="form-group">
<label style="font-weight: bold;">{{ form.message_field.label }}</label>
<input type="text" class="form-control" name="message" id="message">
<br />
<button type="submit" class="btn btn-primary btn-lg btn-block">Encrypt Message</button>
</div>
</form>
I'm new to python and CS so this question might be a bit too easy. Thanks for your help I'm getting an error:
Bad Request
The browser (or proxy) sent a request that this server could not understand.
After implementing a new html template and python function:
#app.route("/register", methods=["GET", "POST"])
def register():
"""Register user."""
session.clear()
if request.form["name"] == "" or request.form["password"] == "":
return render_template("apology.html")
elif request.form["password"] != request.form["confirmation"]:
return render_template("apology.html")
hash = pbkdf2_sha256.hash("password")
do.execute("INSERT INTO finance (name, password) VALUES(:name, :password)",
name=request.form.get["name"], hash=hash)
session["user_id"] = rows[0]["id"]
return redirect(url_for("index"))
{% extends "layout.html" %}
{% block title %}
Register
{% endblock %}
{% block main %}
<form action="{{ url_for('register') }}" method="post">
<fieldset>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text"/>
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<input class="form-control" name="confirmation" placeholder="Confirm Password" type="password"/>
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Register</button>
</div>
</fieldset>
</form>
{% endblock %}
First you should check if the request type is 'POST', after that you check all the conditions. Do like below to resolve the issue:
#app.route("/register", methods=["GET", "POST"])
def register():
"""Register user."""
session.clear()
if request.method == 'POST':
if request.form["name"] == "" or request.form["password"] == "":
return render_template("apology.html")
elif request.form["password"] != request.form["confirmation"]:
return render_template("apology.html")
hash = pbkdf2_sha256.hash("password")
do.execute("INSERT INTO finance (name, password) VALUES(:name, :password)",
name=request.form.get["name"], hash=hash)
session["user_id"] = rows[0]["id"]
return redirect(url_for("index"))
else:
// you can render the template to be shown for registration.
First of all, I've searched this error, tried everything those guys said but it won't work for me.
So, basically, I'm having a login form, and I can't even access the page as it gives me the 400 Bad Request error.
My flask code:
#app.route('/', methods=['POST', 'GET'])
def login():
users = mongo.db.users
login_user = users.find_one({'name' : request.form['username']})
if login_user:
if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password'].encode('utf-8')) == login_user['password'].encode('utf-8'):
session['username'] = request.form['username']
return redirect(url_for('index'))
return 'Invalid username/password combination'
My HTML form:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form method=POST action="{{ url_for('login') }}" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input type="text" class="form-control" name="username" placeholder="Username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" name="pass" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary btn-block">Log In</button>
</form>
<br>
</div>
</div>
I have a similar register page but that works fine, it adds the user to the DB.
I have fixed it. I had to include if request.method == 'POST' under the login index. No idea how I didn't come to this earlier, it makes sense that I was requesting something from the form when I didn't even had the chance to type.
Thanks everyone.
Your html form should be render by login view because in your login view you are trying to get form value:
#app.route('/', methods=['POST', 'GET'])
def login():
...
return render_template('your_htmlform.html')
And now in your form action you can add action={{url_for('index')}} if form submitted.