Can I surpass HTML 'required' field on 'cancel' button press? - python

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

Related

Two HTML Forms in one DJango views

I have two simple HTML forms on one page. I want to create Django view to submit multiple Django forms. I can submit form1 but I have no clue how to submit form2.
There is lot of material on internet but they are all about Djanog forms. Please help me with HTML form submission.
HTML Form
<form action="" method=post name="form1" id="form1">
<input type="text" id="input_form1" name="input_form1">
<button type="submit">Submit</button>
</form>
<form action="" method=post name="form2" id="form2">
<input type="text" id="form2" name="form2">
<button type="submit">Submit</button>
</form>
Views.py
def index(request):
if request.method == 'POST':
input_form1 = request.POST.get('input_form1')
return render(request, 'index.html', params)
Please elaborate how to integrate form2 in Views.py
you can put hidden input inside of each form to identify them
index.html
<form action="" method="post">
{% csrf_token %}
<input type="text" id="input_form1" name="input_form1">
<button type="submit">Submit</button>
<input type="hidden" name="which_form_is_it" value="this_is_form_1">
</form>
<form action="" method="post">
{% csrf_token %}
<input type="text" id="input_form2" name="form2">
<button type="submit">Submit</button>
<input type="hidden" name="which_form_is_it" value="this_is_form_2">
</form>
views.py
def index(request):
if request.method == 'POST':
#watch output in console
print(request.POST)
which_form_is_submiting = request.POST["which_form_is_it"]
if str(which_form_is_submiting) == "this_is_form_1":
#here is yor logic for data from form 1
form_1_input = request.POST["input_form1"]
if str(which_form_is_submiting) == "this_is_form_2":
#here is your logic for data from form 2
form_2_input = request.POST["input_form2"]
return render(request, 'index.html', params)

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!
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)

Flask request.form[] not pulling data

I am trying to post a simple html form and pull the data into python/flask. request.form does not appear to be pulling my form data.
I have a function created to pull the variables if the request method is POST, but the URL ends up with the variables being blank. See code below
#app.route('/inquire',methods=['POST','GET'])
def inquire():
if request.method == 'POST':
name = request.form['dname']
email = request.form['demail']
message = request.form['dmessage']
return
redirect(url_for('inquire_success',name=name,email=email,message=message))
return render_template('inquire.html')
#app.route('/inquiresuccess/',methods=['POST','GET'])
def inquire_success(name,email,message):
return render_template('inquiresuccess.html',name=name,email=email,message=message)
the html below :
<div class="container">
<div class="main">
<form method="post" class="form" action="{{
url_for('inquire_success' }}">
<h2>Inquire below and we'll get back to you</h2>
<label>Name :</label>
<input type="text" name="dname" id="dname" value="name">
<label>Email :</label>
<input type="text" name="demail" id="demail" value="email">
<label>Project info :</label>
<textarea class="messagebox" name="dmessage" id="dmessage"
value="message">
</textarea>
<input type="submit" name="submit" id="submit" value=Submit>
</form>
I would like the code to redirect me to inquiresuccess.html with the variables displayed. Thanks for any help.
The form looks to be posting to the wrong endpoint. Try changing
<form method="post" class="form" action="{{ url_for('inquire_success' }}">
to
<form method="post" class="form" action="{{ url_for('inquire' }}">

Python Flask submit button problems

The "send..." button is not working, index page is running, drop-down menu ok, but when I click the "send..." nothing happen. (Result.html is ok, but empty of course) Any idea, what is the problem?
I've got these .py file:
from flask import Flask, request, render_template
from flask_wtf import Form
from flask_wtf import FlaskForm
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def index():
return render_template('index.html')
#app.route('/result/', methods=['POST', 'GET'])
def result():
vehicle = request.form.get('wine')
year = request.form.get('year')
return render_template('result.html', vehicle=vehicle, year=year)
And two .html of course. index.html:
<!DOCTYPE html>
<html>
<body>
<h1>Submitting</h1>
<form action="/result" method="POST">
<label for="wine">wine</label>
<select id="wine" name="wine">
<option>red</option>
<option>white</option>
<option>rose</option>
</select>
<label for="year">Year</label>
<select id="year"name="year">
<option>1972</option>
<option>1999</option>
<option>2010</option>
</select>
</form>
<br>
<button type="submit" value="submit">send...</button>
</body>
</html>
The result.html:
<!DOCTYPE html>
<html>
<body>
{{ vehicle }} {{ year }}
</body>
</html>
replace your HTML with this HTML. you need to put submit button inside form tag to make it work.
<body>
<h1>Submitting</h1>
<form action="/result" method="POST">
<label for="wine">wine</label>
<select id="wine" name="wine">
<option>red</option>
<option>white</option>
<option>rose</option>
</select>
<label for="year">Year</label>
<select id="year"name="year">
<option>1972</option>
<option>1999</option>
<option>2010</option>
</select>
<button type="submit" value="submit">send...</button>
</form>
<br>
</body>
</html>
maybe you need to put your button in form tag ?
<form action="/result" method="POST">
...
<button type="submit" value="submit">send...</button>
</form>

400 Bad Request Flask

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.

Categories

Resources