In my flask+sqlite app, i have created two buttons for updating and deleting the data respectively. It is working fine for inserting, but when deleting the records, records are not deleting. This is my first learning project with CRUD implementation.
app.py
from flask import Flask, render_template, g, request, redirect, url_for
import sqlite3
app = Flask(__name__)
def connect_db():
connection = sqlite3.connect('./books.db')
connection.row_factory = sqlite3.Row
return connection
def get_db():
if not hasattr(g, 'sqlite3'):
g.sqlite3_db = connect_db()
return g.sqlite3_db
@app.route("/")
def main():
return render_template('book.html')
@app.route('/', methods=['POST'])
def delete(book):
if request.method == "POST":
if request.form['submit'] == 'delete':
db = get_db()
cursor = db.execute("delete from books where book = ?", book)
db.commit()
return redirect(url_for('view'))
@app.route('/view', methods=["GET"])
def view():
db = get_db()
cursor = db.execute('select * from books')
rows = cursor.fetchall()
return render_template('view.html', rows=rows)
if __name__ == '__main__':
app.run(debug=True)
View.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BookStore</title>
</head>
<body>
<h1> Use this page for adding,deleting book from records </h1>
<form action="" method="POST" >
<label for="book">Book</label>
<input type="text" id="book" name="book"><br><br>
<label for="author">Author</label>
<input type="text" id="author" name="author"><br><br>
<label for="category">Book Category</label>
<select name="category" id="category">
<option value></option>
<option value="Fiction">Fiction</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Business">Business and Management</option>
<option value="Biography">Biography</option>
</select><br><br>
<button type="submit" name="submit" value="update">update</button>
<button type="submit" name="submit" value="delete">delete</button>
</form>
</body>
</html>
bookis different in SQLite than the input? Also, the DB-API specifies that the 2nd argument to.execute()should be a container. So, try instead:db.execute("delete from books where book = ?", (book,))where the parens/brackets and comma make a tuple.