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.
Related
I am learning Flask and i started my first project using this framework. At the moment I want to save the user input to the database but I am getting a
TypeError: The view function for 'bookingPage' did not return a valid response.
The function either returned None or ended without a return statement. I checked my function and the return statement must return the booking page in case if it is a GET request and redirect to the main page in case if it is a POST request.
I also checked other posts here regarding such error, but there are answers like "you need to add the return statement". In my case the return statement is present
Here is the code of my function:
#app.route('/booking', methods=['POST', 'GET'])
def bookingPage():
if request.method == 'POST':
firstname = request.form['firstname']
lastname = request.form['lastname']
phone = request.form['phone']
email = request.form['email']
birthdate = request.form['birthdate']
booking_date = request.form['booking_date']
booking_time = request.form['booking_time']
guests_nr = request.form['guests_nr']
notes = request.form['notes']
reservation = Booking(CustomerFname=firstname, CustomerLname=lastname, CustomerPhone=phone, CustomerEmail=email,
CustomerBirthdate=birthdate, ReservationDate=booking_date, ReservationTime=booking_time,
NumberOfGuests=guests_nr, CustomerNotes=notes)
try:
db.session.add(reservation)
db.session.commit()
return redirect('/')
except:
return "An error has been occurred. Please, try again later"
else:
return render_template('booking.html')
Also here is the code of the html
<div class="booking-container">
<form method="post">
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="First Name" required>
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Last Name" required>
<input type="text" name="email" id="email" class="form-control" placeholder="Email" required>
<input type="text" name="phone" id="phone" class="form-control" placeholder="Phone Number" required>
<input type="text" name="birthdate" id="birthdate" class="form-control" placeholder="Date of Birth" required>
<input type="text" name="booking_date" id="booking_date" class="form-control" placeholder="Reservation Date" required>
<input type="text" name="booking_time" id="booking_time" class="form-control" placeholder="Reservation Time" required>
<input type="text" name="guests_nr" id="guests_nr" class="form-control" placeholder="Number of Guests" required>
<textarea name="notes" id="notes" class="form-control" placeholder="Notes"></textarea>
<input type="submit" class="btn-submit" value="Sent">
</form>
</div>
the issue is solved. I made a stupid mistake there:
In
def booking():
if request.method == 'POST':
must be ['POST'] instead of 'POST'
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.
I'm trying to access a request from an HTML form, and send it as a mail, but I get a mail with a value of "None",
here is my code:
#app.route("/about", methods=['GET', 'POST'])
def send_message():
name = request.form.get('name')
msg = Message(
subject='Hello ' + str(name),
sender='kristofferlocktolboll#gmail.com',
recipients=
['kristofferlocktolboll#gmail.com'],
html=render_template("about.html"))
mail.send(msg)
confirm_msg = "Your message has been sent!"
return render_template("about.html", confirm_msg=confirm_msg)
I think it might be due to the fact, that I'm casting the object into a string, but if I don't do that, I will get an error due to making a conjunction between a String and another object
EDIT:
here is my html code, I have tried both using post and get as the method, but nothing works.
<form action="/send_message" method="post">
First name: <br>
<input type="text" name="name" size="35"><br>
Last name:<br>
<input type="text" name="lastname" size="35"><br>
Email-address: <br>
<input type="email" name="email" size="35"><br>
Phone-number: <br>
<input type="text" name="phone" size="35"><br>
Enter your message: <br>
<textarea type="text" name="message" rows="7" cols="40"></textarea><br>
</form>
EDIT 2:
When ever I try to display the confirm_msg it is displayed instantly, when I enter the site.
<p>{{confirm_msg}}</p>
Firstly you must add CSRF_TOKEN for your form:
<form method="post" action="/send_message">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
...
.....
</form>
Also can you tell us in which page you are trying to see <p>{{confirm_msg}}</p> ?
'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>
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.