I am trying to execute a simple python function, Through which I want to update database dynamically though a bootstrap modal window. Unable to Identify any mistake there... and the same error occurs again... kindly help me out here..
from flask import Flask, render_template, redirect, json, request,session, url_for, jsonify
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash
#app.route('/updatepost', methods = ['POST', 'GET'])
def updatepost():
try:
if session.get('user'):
_posttitle = request.form['postt']
_postcontent = request.form['postd']
_postiid = request.args.get('id')
con = mysql.connect()
cursor = con.cursor()
print 555
#cursor.execute("UPDATE addpost SET post_title= 'apple' , post_content ='a fruit' WHERE Id = '" + _postiid + "'")
cursor.execute("UPDATE addpost SET post_title='" + str(_posttitle) + "', post_content ='" + str(_postcontent) + "' WHERE Id = '" + str(_postiid) + "'")
con.commit()
return redirect('/userhome')
cursor.close()
con.close()
else:
return redirect('/')
except Exception as e:
return render_template('error.html', error = str(e))
My html code..
<div class="modal fade" id="editModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×
</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="editModalLabel">Edit Update</h4>
</div>
<div class="modal-body">
<form role="form" method= POST>
<div class="form-group">
<label for="recipient-name" class="control-label">Title:</label>
<textarea class="form-control" name="postt" id="editTitle"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="control-label">Description:</label>
<textarea class="form-control" name="postd" id="editDescription"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="btnUpdate" name = "abc" type="button" onclick = "proceedupdate()" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
</div>
it would seem that you are not handling your request.post under updatepost():
#app.route('/something', methods=['GET', 'POST'])
def something():
"""
form, retrieves variables when using POST
"""
try:
if request.method == 'POST':
#do something
else:
#do something else
except Exception as e:
print(e)
since in your html you are specifying the post method upon form submition:
form role="form" method= POST>
you should be handling the "POST" within def updatepost(): at the moment it only handles GET requests, and does nothing if the request method is POST.
Related
I'm new to Python and trying to develop simple web application.
In the code below I am trying to retrieve values from DB and rending on HTML page
I'm able to see the HTML page but not values passed. Please help me here.
Python code
#app.route('/userDetails', methods=['POST', 'GET'])
def userDetails():
if request.method == 'POST':
print('in get method')
userid = request.form['userId']
print('user id ', userid)
conn = mysql.connect()
cursor = conn.cursor()
# Get User Details
print('execut sql')
result = cursor.execute("SELECT * FROM tbl_user WHERE user_id= %s", [userid])
if result > 0:
data = cursor.fetchall()
for row in data:
userId = row[0]
name = row[1]
userName = row[2]
password = row[3]
return render_template("userDetails.html", userId=userId, name=name, userName=userName, password=password)
else:
return render_template('index.html')
cursor.close()
HTML code below.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<title>Python Flask Bucket List App</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h3 class="text-muted">Python Flask App </h3>
</div>
<div class="jumbotron">
<h1>Display User Details</h1>
<div class="jumbotron">
<form class=class="form-userDetails, action="/userDetails", method="POST">
User ID:<input type="text" name="userId" class="form-control">
Name <output name="name" id="name" for="userId" class="form-control"></output>
User Name <output name="userName" id="userName" for="userId" class="form-control"></output>
Password <output name="password" id="password" for="userId" class="form-control"></output>
</br>
<button id="btnretive" class="btn btn-lg btn-primary btn-block" type="submit">Retrive</button>
</form>
</div>
<div class="Footer">
<footer class="footer">
<p>© Company 2015</p>
</footer>
</div>
</div>
</body>
</html>
#DRaj, you are using <output> tag in incorrect way. From the specification,
The HTML Output element () is a container element into which a site or app can inject the results of a calculation or the outcome of a user action.
For more info and example refer to this Mozilla page.
Now,
Flask uses Jinja2 template engine for its HTML rendering. So, the correct way to output values would be to enter a python variable inside Expression delimiters {{ ... }} in the HTML and pass the variables to render_template method.
i.e.
<form class=class="form-userDetails, action="/userDetails", method="POST">
User ID:<input type="text" name="userId" class="form-control">
Name: {{ name }}
User Name: {{ userName }}
Password: {{ password }}
</br>
<button id="btnretive" class="btn btn-lg btn-primary btn-block" type="submit">Retrive</button>
</form>
and the python code should be:-
return render_template("userDetails.html", name=name, userName=userName, password=password)
Refer to this Jinja template designer documentation for more information.
'main' is just my homepage and '/' is the url. For some reason, I can't get signUp to return back to the homepage after finishing.
I can also confirm 'here' and 'Registered' get printed. Also, in my terminal, i get
127.0.0.1 - - [23/Apr/2018 23:13:51] "GET / HTTP/1.1" 200 -
Which means it SHOULD be going to home, because I get the same line when I just click the home link on the page through html. Clicking the link redirects too. It also is the same path '/', so I'm not sure why it works with html but not with flask when I know the redirect gets acknowledged.
What happens with the flask is it just stays on the signup page. Nothing else, no errors thrown. Just sits there.
I was even able to do redirect('main', code=307) and it actually ran code on the main page. So why wouldn't this simple redirect render Senty.html and take the user to the page?
#app.route("/")
def main():
return render_template('Senty.html')
#app.route('/signUp',methods=['POST','GET'])
def signUp():
# still need to create signup class and transfer below code to new file
conn = mysql.connect()
cur = conn.cursor()
try:
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
# validate the received values
if _name and _email and _password:
cur.callproc('sp_createUser',(_name,_email,_password,))
print ("Registered")
data = cur.fetchall()
conn.commit()
json.dumps({'message':'User created successfully !'})
print('here')
return redirect(url_for('main'))
#else:
#return json.dumps({'html':'<span>Enter the required fields</span>'})
#except Exception as e:
#return json.dumps({'error':str(e)})
finally:
cur.close()
conn.close()
return redirect(url_for('main'))
I'm not sure where to go. I feel like I've tried everything. Here is also the HTML
<div class="jumbotron">
<h1>Senty App</h1>
<form method="POST">
<label for="inputName" class="sr-only">Name</label>
<input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required>
<button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Sign up</button>
</form>
</div>
This question already has an answer here:
Number of MySQL query parameters match arguments passed to execute, but Python raises "not all arguments converted"
(1 answer)
Closed 5 years ago.
Hi I am having difficulties inserting values into my database.
I am able to log in using the same method I use for the sign up page.
I have tried a lot of different options but nothing seemed to work.
Here is my python code:
from flask import Flask, request, render_template, url_for
import pymysql.cursors
app = Flask(__name__)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='1234',
db='mydb',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
#app.route('/')
def index():
return render_template('signup.html')
#app.route('/signup', methods=['POST', 'GET' ])
def signup():
cursor = connection.cursor()
if request.method == 'POST':
try:
cursor.execute('''INSERT INTO users (user, fname, lname, email, pnum, password) VALUES (%s, %s, %s, %s, %s, %s)''')
cursor.commit()
finally:
return render_template('login.html')
if __name__ == '__main__':
app.run(debug=True)
and my HTML:
<h1>Please Sign Up</h1>
<button onclick="document.getElementById('id01').style.display='block'"style="width:auto;">Sign Up</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal-content animate" action="/signup" method="POST">
<div class="container">
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<label><b>user</b></label>
<input type="text" placeholder="user" name="user" required>
<label><b>First name</b></label>
<input type="text" placeholder="First name" name="fname" required>
<label><b>pnum</b></label>
<input type="text" placeholder="Pnum" name="pnum" required>
<label><b>Last name</b></label>
<input type="text" placeholder="Last name" name="lname" required>
<input type="checkbox" checked="checked"> Remember me
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" action="/Signup" method="POST" class="signupbtn">Sign Up</button>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
You could do something like:
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('abc#python.org', 'very-secret'))
Pay special attention to " " and back-ticks `` in the query. Your query seems to be faulty. There are no values for the placeholders %s.
Hope that helps.
I am trying to get a list of values from checkboxes.
I found a post that looks to solve my issue (How to get if checkbox is checked on flask), however, I am continuing to receive this error: Bad Request The browser (or proxy) sent a request that this server could not understand.
I'll post my entire code block to put it in context, but without the checkboxes added, it works fine. In fact, I had the same options as a drop-down menu and it was working fine.
Please note that although I code in python on a regular basis, I am a beginner to html and flask.
<form action='/user_rec' method='POST' id='submitform'>
<input type='text', placeholder='user id' name='user_input'>
<button type="submit" class="btn btn-success">Recommend</button>
<br><br>
<h2>Other Options</h2>
<h5>Best Number of Players</h5>
<div class="checkbox">
<label><input type="checkbox" name="check" value="1">1</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="check" value="2">2</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="check" value="3">3</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="check" value="4">4</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="check" value="5">5+</label>
</div>
<h5>Minimum Play Time (minutes)</h5>
<input type="text", placeholder='0' name='min_time'>
<br><br>
<h5>Maximum Play Time (minutes)</h5>
<input type="text", placeholder='500000' name='max_time'>
</form>
and my python code:
#app.route('/user_rec', methods=['POST'])
def button1():
user_name = (request.form['user_input'])
best_num_player = (request.form['best_num_player'])
min_time = (request.form['min_time'])
max_time = (request.form['max_time'])
players = request.form.getlist('check')
I think there are two problems with your code:
'best_num_player' is not a key in the form dict.
You didn't return a redirect after posting.
Here's an example app.py that you can try. (I assumed you named the template index.html)
from flask import Flask, render_template, redirect, request
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/user_rec', methods=['POST'])
def user_rec():
user_name = request.form.get('user_input')
min_time = request.form.get('min_time')
max_time = request.form.get('max_time')
players = request.form.getlist('check')
print(user_name, min_time, max_time, players)
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
I keep getting a 400 Bad Request when I try to run my Flask project.
I have to do a project using Flask and HTML, and it was supposed to be a group project, so members would have to learn different parts of it to then gather everything. Sadly, my 'group' didn't do anything at all
Here's my code:
Flask
app = Flask(__name__, static_url_path="")
#app.route('/', methods=['POST','GET' ]) #1 - Login e criar conta
def PagInicio():
button = request.form["button"]
if request.method == 'POST':
if button == "login":
return render_template("Princ.html")
elif button =="criar":
return render_template("Criar.html")
else:
return render_template("Inicio.html")
return render_template("Inicio.html")
HTML:
<div class="col_12">
</div>
<!-- Tab 3 - Perfil -->
<div id="tabr3" class="tab-content">
<div class="grid">
<div class="col_2"></div>
<div class="col_8">
<form class="vertical" method="POST" action="/">
<fieldset>
<div class="grid">
<div class="col_6">
<label for="usuario">Usuário</label>
<input id="usuario" name="usuario" type="text" />
</div>
<div class="col_6">
<label for="senha">Senha</label>
<input id="senha" name="senha" type="password" />
</div>
<div class="col_12 center">
<button class="medium" value="login"</i> Login</button>
</div>
<div class="col_12 center">
<button class="medium" value="criar"</i> Criar</button>
</div>
</form>
</div>
<div class="col_2"></div>
</div>
</div>
</div>
<div class="col_1"></div>
</div>
You are trying to access the request.form dictionary, always:
button = request.form["button"]
This throws a 400 response error if there is no such value in the form. This is always the case when you have a GET request, request.form is only populated when there is POST data in a valid format.
Only try to access the button when you already confirmed you have a POST request:
def PagInicio():
if request.method == 'POST':
button = request.form["button"]
if button == "login":
return render_template("Princ.html")
elif button =="criar":
return render_template("Criar.html")
else:
return render_template("Inicio.html")
return render_template("Inicio.html")
Next, you don't actually have any form element named button. You have button form elements but none have a name. Give all your buttons the same name attribute, varying the value attribute:
<div class="col_12 center">
<button class="medium" name="button" value="login"> Login</button>
</div>
<div class="col_12 center">
<button class="medium" name="button" value="criar"> Criar</button>
</div>
Note that you malformed the <button tags too.