How do I reference input in flask python? [duplicate] - python

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
How do I reference input in a python flask code, for some reason request.form doesn't seem to be working. Here's the code:
#app.route("/post_field", methods=["GET", "POST"])
def need_input():
forum = ['def']
inputf = request.form["fname"]
if inputf == 'test':
forum.append(inputf)
return """
<html>
<body>
<p>
<font face="Times New Roman" size="+2" color="#870012">{forum}</font>
<form method="post" action=".">
<p>
<input id="fname" name="fname"</p>
</form>
</body>
</html>
""".format(forum=forum)

I believe this is what you want:
number = 0
#app.route("/post_field", methods=["GET", "POST"])
def need_input():
if request.method == "POST":
if "fname" in request.form:
number += int(request.form["fname"])
else if request.method == "GET":
return f"""
<html>
<body>
<p style="font-family: 'Times New Roman'; size: 2vw; color: '#870012'">{number}</p>
<form method="post">
<input id="fname" name="fname"</p>
</form>
</body>
</html>
"""

If you want to get a specific field from the form, you need to use:
request.form.get('fname')
You'd be much better off using Jinja and Render Template rather than doing it this way. It would make your code much more scalable.

Related

What's wrong with this Flask request? [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
I have been working with flask for a long while, but after a break from it, I cant seem to figure out what's wrong here.
index.html:
<input name="linkHolder" type="url" class="defaultTextBox advancedSearchTextBox link" placeholder="http://www.youtube.com">
<form method="POST" action="/button">
<input class="btn" type="submit">Go</input>
</form>
main.py:
#app.route('/button', methods=["GET", "POST"])
def button():
if request.method == "POST":
dlink = request.form.get("linkHolder")
print(dlink)
return render_template("index.html", dlink=dlink)
I'm sorry if its a simple answer but my end goal here is to load the link typed by the user, print said link, and then reload the page. What am I doing wrong?
In your index.html, your <form> tag does not include the linkHolder input.
Do the following:
<form method="POST" action="/button">
<input name="linkHolder" type="url" class="defaultTextBox advancedSearchTextBox link" placeholder="http://www.youtube.com">
<input class="btn" type="submit">Go</input>
</form>
You might also need an if statement in main.py that actually renders the page
#app.route('/button', methods=["GET", "POST"])
def button():
if request.method == "GET":
return render_template("index.html")
if request.method == "POST":
dlink = request.form.get("linkHolder")
print(dlink)
return render_template("index.html", dlink=dlink)
You need a form with the name
Also, your tag </input> input doesn't have any closing tag you should be using button tag
<form method="POST" action="/button">
<input type="text" name="linkHolder">
<button class="btn" type="submit">Go</button>
</form>

How do I use global variable 'adopt' in 2 functions? [duplicate]

This question already has answers here:
How to pass a variable between Flask pages?
(2 answers)
Closed 2 years ago.
I'm making an otp authentication for admin in my website, but as I'm trying to use this 'adopt' variable in my 'adrelog' function, it gives the error that 'adopt' variable is not defined. Please help me find out how to use this variable in 2 functions.
python code :
#admin password reset logic
adopt=" "
#app.route("/admin_repass", methods=["GET","POST"])
def Admin_reset_pass():
email=str(request.form.get("email"))
details=db.execute("select email from admin_master_tbl").fetchall()
message="email not found"
message1="enter your otp"
for det in details:
if email in det[0]:
string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
length = len(string)
otp=""
for i in range(6) :
otp += string[math.floor(random.random() * length)]
global adopt
adotp=otp
msg = Message("Subject", recipients=[email])
msg.body = adopt
mail.send(msg)
return render_template("admin_relogin.html", message=message1)
else:
return render_template("admin_pass_reset.html", message=message)
#app.route("/admin_otp", methods=["GET","POST"])
def adrelog():
global adopt
message="login successfull"
cotp=str(request.form.get("otp"))
if adopt==cotp:
return render_template("index.html", message=message)
else:
return "login failed"
html code 1 :
<html>
<body>
<h2>{{message}}</h2>
<form action="{{ url_for('Admin_reset_pass') }}" method="post" align:"center">
<input type="text" name="email" placeholder="enter your mail for reset request">
<button>submit</button>
</form>
</body>
</html>
html code 2:
<html>
<body>
<form action="{{ url_for('adrelog') }}" method="post">
<input type="text" name="otp" placeholder="enter your otp">
<button>submit</button>
</form>
</body>
</html>
You can store them in session storage and access them in any view.

Flask, why does request.form runs error 400?

I am trying to extract text from the following HTML code:
#app.route("/", methods=['GET', 'POST'])
def home():
if request.method == 'POST':
H_desiderata = float(request.form.get('H_desiderata')) #THIS CAUSES THE ERROR
return render_template('form1.html')
HTML below:
<body>
<h2>Brioche Recipe</h2>
<form>
<div class="grid-container">
<div class="grid-item">
<label class="text" for="H_desiderata">
H_desiderata:
</label><be>
<input type="number" id="H_desiderata" name="H_desiderata1"
value={{val_H_desiderata}} min="1" max="99" step="1"><br>
Before putting it into a grid it worked:
old working code:
<form>
<label for="H_desiderata">H_desiderata:</label><br>
<input type="number" id="H_desiderata" name="H_desiderata"
value={{val_H_desiderata}} min="1" max="99" step="1"><br>
How should I adapt request.form to return the value within the input box?
There is so much wrong with your code, but let's start with this:
request.form is empty when request.method == "GET. So. request.form['H_desiderata'] will give a key error.
Move that to the POST section of your view. Also, use request.form.get('H_desiderata', -9999999) in case it's not defined.
UPDATE:
OK, now try:
if request.method == 'POST':
print(request.form)
print(request.form.get('H_desiderata'))
print(float(request.form.get('H_desiderata')))
H_desiderata = float(request.form.get('H_desiderata'))
Then, you are going to want:
return render_template('form1.html', val_H_desiderata=H_desiderata)
UPDATE2:
Your <form> tag is malformed. Try:
<form action="/" method="post">
UPDATE3:
You change the name of the input, so change to: request.form.get('H_desiderata1')

Flask does not render my modified page when asked [duplicate]

This question already has answers here:
Reload Flask app when template file changes
(13 answers)
Closed 4 years ago.
I have a page with a simple text and a button in a form
<html>
<head>
</head>
<body>
<h1>JASON</h1>
<form>
<button type="submit" formmethod="POST">Activate</button>
<br>
<input type="hidden" value="act.12344" name="sub" />
</form>
</body>
</html>
And this python script
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
#app.route('/atdt', methods=['GET', 'POST'])
def atdt():
if request.method == 'POST':
print('post')
requested = request.form['sub']
ver = str(requested).split('.')
if ver[0] == 'act':
print('act')
modif(ver[1]) #this func modifies the index page
return render_template('index.html')
else:
return render_template('index.html')
The point of the script is to change the name jason in something else...and it works well, the page is changed and its all good
But my flask program wont show it...the '.html' page its changed, and if I open it manually, outside the program it works!
But if i give python the line return render_template('index.html') but it wont render it
If i try to refresh manually it will just show me the old page
Any help ?
You are not modifying the html, You are just calling a function that returns modified version of an input!
First of all you have to use tempalte engine
Your HTML Should be something like this:
<html>
<head>
</head>
<body>
<h1>{{name}}</h1>
<form>
<button type="submit" formmethod="POST">Activate</button>
<br>
<input type="hidden" value="act.12344" name="sub" />
</form>
</body>
</html>
And your view should look like this:
#app.route('/atdt', methods=['GET', 'POST'])
def atdt():
if request.method == 'POST':
print('post')
requested = request.form['sub']
ver = str(requested).split('.')
if ver[0] == 'act':
print('act')
name = modif(ver[1]) #this func modifies the index page
return render_template('index.html', name=name)
else:
return render_template('index.html', name="JASON")
The template engine will handle The name change
Flask uses Jinja2 Template Engine, You can read more about it here

Flask Saving a selected value from a field and displaying it on another page

I'm new to Flask and am facing difficulties saving the value that is selected from an option of four different coffee roasts and displaying it on another page. One one page (Roast.html) the user has the option to select one coffee roast from Light, Medium, Dark, and Special. After the submit button is pressed, I want to show this selection on the next page (Brew.html) i.e. "Your _____ roast coffee is now brewing!" Any help would be greatly appreciated! I would prefer not to involve php or javascript in this code. Thank you
coffeeMaker.py:
from flask import Flask
from flask import render_template
from flask import url_for
from flask import request
app = Flask(__name__)
#app.route('/')
def welcome():
return render_template("welcome.html")
#app.route('/Roast', methods = ['GET','POST'])
def roast():
print "inside Roast"
return render_template("Roast.html")
#app.route('/Brew', methods = ['GET','POST'])
def brew():
if request.method == 'POST':
print 456
a = request.query_string
print 789
return render_template("Brew.html",selection = a )
else:
return "This is a GET request."
if __name__ == '__main__':
app.run()
welcome.html:
<html>
<head>
<title>Welcome to Coffee Maker</title>
</head>
<body>
<h1>This is a website for you to order your coffee of perference
</h1>
<a href = "/Roast" >ready for a coffee</a>
</body>
</html>
Roast.html:
<html>
<form action="/Brew" method="Post">
<h3>2. Choose your Roast</h3>
<input type="text" name="firstname" value="Mickey">
<br>
<input type="radio" name="roastType" value="Light">Light
<br>
<input type="radio" name="roastType" value="Medium" checked>Medium
<br>
<input type="radio" name="roastType" value="Dark">Dark
<br>
<input type="radio" name="roastType" value="HackGT Blend">Special Blend
<br><br>
<input type="submit" value="Brew It">
</form>
</html>
Brew.html:
<html>
<head>
<title>
brew
</title>
</head>
<body>
<h1> Brewing</h1>
<p>You selected{{selection}}</p>
<p>Get ready for your perfect cup of coffee~</p>
</body>
</html>
You just need to grab the element from the request.form object:
if request.method == 'POST':
brew_type = request.form["roastType"]
print(brew_type)
return render_template("Brew.html", selection=brew_type)
It's all covered in the quickstart guide.

Categories

Resources