Retrieving Form Input using flask python Not working [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.
#app.route('/signup',methods=["GET","POST"])
def signup():
return render_template('signup.htm')
password = request.form['password']
if password =="python":
return redirect(url_for("home"))
This is my python code for retrieving form input and then to redirect the user to the home page if the password is "python".
<form action="#" method="POST" name="password">
<input type="password" class="form-control"
id="exampleFormControlInput1" placeholder="Password">
</form>
This is the respective HTML code for the signup page.

you are using name="password" in your form attributes which is wrong. You have to use it in attributes of input
So HTML should be like this
<form action="#" method="POST"><input type="password" name="password" class="form-control" id="exampleFormControlInput1" placeholder="Password"></form>
Also in python you are returning first which is also wrong return is last statement of function
So python code must be like this
#app.route('/signup',methods=["GET","POST"])
def signup():
if(requset.method == 'POST'):
password = request.form['password']
if password =="python":
return redirect(url_for("home"))
else:
return render_template('signup.htm')

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.

Is there a way to pass a variable to the html form action attribute?

I'm a newbie at programming and require your assistance -
In my python/flask routes.py script, I have a couple of app.routes. I would like to pass the name of the route to an html form action field, such that the values in the form are posted to the route of that name;
#app.route('/interfaceStats', methods=['GET', 'POST'])
def interfaceStats():
routeName='interfaceStats'
hostname = request.form['hostname']
username = request.form['username']
password = request.form['password']
command = ['python', 'readOperData.py', hostname, username,password]
print(command)
subIntObject = subprocess.check_output(command, shell=False)
intObjectInString = subIntObject.decode('ascii')
interfaceObjInJsonify = jsonify(intObjectInString)
interfaceObjInJson = json.loads(intObjectInString)
return render_template('interfaceStats.html', interfaceObjInJson=interfaceObjInJson, hostname=hostname)
<form id="submit-form" action={{routeName}} method="POST">
Hostname:
<input type="text", name="hostname" required>
Username:
<input type="text" name="username" required>
Password:
<input type="password" name="password" required>
<br>
<input type="submit" id="submit-form" class="hidden" />
</form>
Error:
the requested URL was not found on the server. If you entered the URL
manually please check your spelling and try again.
192.168.254.1 - - [09/May/2019 15:49:56] "GET /method=%22POST%22?hostname=192.168.253.144&username=admin&password=password
HTTP/1.1" 404 -
You need quotes around your action attribute.
<form id="submit-form" action="{{routeName}}" method="POST">

How do I deal with an empty radio input in python [duplicate]

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 4 years ago.
I want to make an if statement that deals with the case when a user doesn't select any radio options. if they don't select a radio option, it just prints out an error message. However, every time I don't select an option it just tells me:
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'mysearch'
HTML:
<form class="anotherform" method="POST">
<div class="myform">
<input type="text" placeholder="Enter your text or leave empty" name="search_term">
</div>
<input type="radio" name="mysearch" value="option1">Option 1<br>
<input type="radio" name="mysearch" value="option2">Option 2<br>
<input type="radio" name="mysearch" value="option3">Option 3<br>
<input type="radio" name="mysearch" value="option4">Option 4<br>
<button class="button" type="submit">Search</button>
</form>
{{error_msg}}
routes.py
#app.route('/search', methods=['POST', 'GET'])
def search():
if request.method == 'POST':
search_filter = request.form["mysearch"]
search_term = request.form["search_term"]
if search_filter == "":
error_msg = 'You didnt select an option'
return render_template('/search.html', error_msg=error_msg)
return render_template('/search.html')
If I'm not mistaken request.form is a Multidict type which is like a Python dictionary.
So you can get a default value from dictionary if you are not sure if the key exists, and avoid throwing the error in your application like this:
search_filter = request.form.get("mysearch", "")
search_term = request.form.get("search_term", "")
And then check search_filterif it is empty or it has value.

Flask : ImmutableMultiDict has no attribute

I wrote a small flask file:
myapp.py
#APP.route('/login', methods=['GET','POST'])
def login():
return flask.render_template('login.html')
#APP.route('/loginNext', methods=['POST','GET'])
def loginNext():
user=request.form.username
passw=request.form.password
return str(user)+str(pass)
login.html
<form id="foo" method="post" action="/loginNext">
Username : <input type="text" name='username' value="admin">
Password : <input type="password" name='password' value="">
<input type="submit" name="submit" value="Submit">
</form>
When I am trying to do request.form.username, I am getting
*AttributeError: 'ImmutableMultiDict' object has no attribute 'username' *
I read on stackoverflow as well as other places but didnot work. I tried doing request.form.get('username',None') that did not fetch the username.
<input type="text" name='username' value="admin"> was your input in .html file so to access in flask It is done in this way
username = request.form['username']
and you get the data as username .. same for password also.
if form tag contains below:-
<input type="text" name='username'>
In Flask Function, we can access it in 2 ways:-
username = request.form['username']
username = request.form.get('username')

Categories

Resources