Update SQL query for HTML table Python - python

I have the following code in my Python project:
<table class="table table-striped">
<tr>
<th>Card Number</th>
<th>Card Name</th>
<th>Card Rarity</th>
<th>Card Quantity</th>
</tr>
{% for card in card_data %}
<tr>
<td>{{card.card_prefix}}</td>
<td>{{card.card_name}}</td>
<td>{{card.card_rarity}}</td>
<td>{{card.card_quantity}}</td>
</tr>
{% endfor %}
</table>
Is there a way to update the quantity to -1 or +1 on a button that only updates one row of the SQL database?
The current code in my main page is:
#app.route('/lob')
def lob():
session.clear()
cur = mysql.connection.cursor()
current_set = 'LOB'
session['set_selected'] = True
session['current_set'] = current_set
result = cur.execute("SELECT * FROM card_list WHERE card_set =%s", [current_set])
card_data = cur.fetchall()
if result > 0:
return render_template('/Booster Packs/lob.html', card_data=card_data)
else:
flash('Set Not Found!', 'danger')
return render_template('/Booster Packs/lob.html')
I can update the question with more information if needed, I'm just not sure how to go about how to select the value to update given the table.
Sorry for the bad English, it is not my first language.

Related

How to autoload html table based on variable in the URL (Python, Flask, Mysql)

Python-
#app.route('/search', methods=['GET','POST'])
def search():
if request.method == "POST":
classname = request.args['class']
cursor.execute("select * from errordata where rule_name like %s", (classname))
conn.commit()
data = cursor.fetchall()
data1 = len(data)
# all in the search box will return all the tuples
if len(data) == 0 and classname == 'all':
cursor.execute("SELECT * from errordata ORDER BY error_date DESC")
conn.commit()
data = cursor.fetchall()
data1 = len(data)
return render_template('search.html', data=data, data1=data1)
return render_template('search.html')
HTML-
<form class="errorboard" method="post" action=""
style="margin:auto;max-width:600px">
<input type="text" placeholder="Search by Rule-Name" name="book">
<div>
Total errors- {{data1}}
</div>
</form>
<table>
<tr bgcolor="#000">
{% for item in data %}
<tr>
<td> {{item[0]}} </td>
<td> {{item[1]}} </td>
<td> {{item[2]}} </td>
<td> {{item[3]}} </td>
<td> {{item[4]}} </td>
<td> {{item[5]}} </td>
<td> {{item[6]}} </td>
<td> {{item[7]}} </td>
<td> {{item[8]}} </td>
</tr>
{% endfor %}
</table>
How to make the HTML table load as soon as I enter the URL, Now I need to click enter or a submit button for the table to load based on the SQL query (Value taken from URL).
Tried to remove the form tag and added the method = POST in table tag, But didnt work. It just goes blank with out a input box for me to submit or enter.

How to limit digits after decimal point in SQlite python?

Hi, sorry if it seems such simple but honestly the solution I find on google (or my implementation) is breaking my code :/
How can i limit the digits as 2 after decimal point. Even it's 2.99999999 I would like to display as 2.30.
TIA
Here my code for this page (working but displays lots of digits after decimal point):
#app.route("/")
#login_required
def index():
"""Show portfolio of stocks"""
# Update the latest price information for the existing stock
user_id = session["user_id"]
stock_list = db.execute("SELECT stock_id, stock_symbol, shares, unit_price, total_price FROM stocks WHERE owner_name == %s", session["user_id"])
# Iterate through dictionaries in the results (list of rows(dicts))
length = len(stock_list)
for i in range(length):
stock_id = stock_list[i]["stock_id"]
symbol = stock_list[i]["stock_symbol"]
amount = stock_list[i]["shares"]
price_dict = lookup(symbol)
price = price_dict["price"]
total = price * amount
# Update stocks table for the logged in user
db.execute("UPDATE stocks SET unit_price = ?, total_price = ? WHERE stock_id = ?", price, total, stock_id)
# Extract updated data and display in the template
rows = db.execute("SELECT stock_symbol, stock_name, shares, unit_price, total_price FROM stocks WHERE owner_name == %s", session["user_id"])
rows2 = db.execute("SELECT cash FROM users WHERE username == %s", session["user_id"])
assets_list = db.execute("SELECT total_price FROM stocks WHERE owner_name == %s", session["user_id"])
stock_assets = 0.00
cash_asset_list = db.execute("SELECT cash FROM users WHERE username == %s", session["user_id"])
cash_asset = cash_asset_list[0]["cash"]
for i in range(len(assets_list)):
stock_assets = stock_assets + assets_list[i]["total_price"]
net_assets = stock_assets + cash_asset
return render_template("index.html", rows=rows, rows2=rows2, net_assets=net_assets)
My HTML template for the page
{% extends "layout.html" %}
{% block title %}
Home
{% endblock %}
{% block main %}
<table class="table table-hover">
<tr class="table-info">
<th scope="col">Symbol</th>
<th scope="col">Company</th>
<th scope="col">Shares</th>
<th scope="col">Price</th>
<th scope="col">TOTAL</th>
</tr>
{% for row in rows %}
<tr class="table-light">
<td>{{ row.stock_symbol }}</td>
<td>{{ row.stock_name }}</td>
<td>{{ row.shares }}</td>
<td>{{ row.unit_price }}</td>
<td>{{ row.total_price }}</td>
</tr>
{% endfor %}
</table>
<table class="table table-hover">
<tr class="table-dark">
<th scope="col">Cash Balance</th>
<th scope="col">Total Assets</th>
</tr>
{% for row2 in rows2 %}
<tr class="table-light">
<td>{{ row2.cash }}</td>
<td>{{ net_assets }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
You can create a function:
def truncate(f):
return math.floor(f * 10 ** 2) / 10 ** 2
And it will return the value without rounding with 2 decimal places.
Then when you do total just set it to the function of the result.
In python you can use the function round to limit the decimal for number of places.
x = 1.4499999
you can use round(x, number of decimal places)
x = round(x, 2)
Final output will be
x = 1.50

Passing data from html to python

It is necessary to obtain information from the selected cell from the html file and then work with it in views.py. Is it possible and how to do it? Thank you in advance!
<tbody>
{% for element in qz %}
<tr>
<td class="counterCell"></td>
<td style="display: none">{{ element.0 }}</td> <!-- information is needed for this cell when it is selected -->
<td>{{ element.1 }}</td>
<td>{{ element.2 }}</td>
<td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
{% endfor %}
</tbody>
views.py:
cursor = connection.cursor()
cursor1 = connection.cursor()
cursor2 = connection.cursor()
cursor.execute(
"SELECT sites.site_title, sites.url FROM sites, my_sites, auth_user WHERE auth_user.id = my_sites.id_user AND sites.id = my_sites.id_site AND auth_user.id =" + str(
request.user.id))
cursor1.execute(
"SELECT sites.site_title, sites.url FROM sites, my_sites, auth_user WHERE auth_user.id = my_sites.id_user AND sites.id = my_sites.id_site AND auth_user.id =" + str(
request.user.id))
cursor2.execute(
"SELECT sites.id, sites.site_title, sites.url FROM sites, my_sites, auth_user WHERE auth_user.id = my_sites.id_user AND sites.id = my_sites.id_site AND auth_user.id =" + str(
request.user.id))
q = [str(row[0]) for row in cursor.fetchall()]
z = [str(row[1]) for row in cursor1.fetchall()]
x = [str(row[0]) for row in cursor2.fetchall()]
qz = [(x[i], q[i], z[i]) for i in range(len(q))]
return render(request, 'main/my_newsagent.html', {'qz': qz})
That what you showing is a template. Template receive a data from a view function.
So that function located in a views.py returning that template, with interpolated data (rendered final html). So in may be in context or in other variable.

Data table python flask

I have a question regarding mysql db python table in Bootstrap.
My question is my data is not shown in the table. I can see it gets data because of when I add row in mysql db with data the table increases.
app.py code:
#app.route('/dashboard')
#is_logged_in
def dashboard():
#create cursor
cur = mysql.get_db().cursor()
#Get data
result = cur.execute("SELECT * FROM test")
data=cur.fetchall()
if result > 0:
return render_template('dashboard.html', data=data)
else:
msg = 'No DOC Found'
return render_template('dashboard.html', msg=msg)
#close connection
cur.close()
return render_template('dashboard.html' )
.html
<table class="table table-striped">
<tr>
<th>data1</th>
<th>data2</th>
</tr>
{% for test in data%}
<tr>
<td>{{test.rdno}}</td>
<td>{{test.ipno}}</td>
{% endfor %}
</tr>
</table>
instead of
<td>{{test.rdno}}</td>
<td>{{test.ipno}}</td>
do this
<td>{{test[0]}}</td>
<td>{{test[1]}}</td>

Unable to insert data to the database but it returns success every time i run it

I want to insert data, which i found by iterating using for loop in jinja template, to a table. when i submit the form returns SUCCESS but nothing is registered on the database.
#app.route('/submit', methods=['GET','POST'])
def submit():
if request.method == 'POST':
cur = connection.cursor()
userDetails = request.form
oracle_id = userDetails.getlist('id')
name = userDetails.getlist('name')
status = userDetails.getlist('status')
remark = userDetails.getlist('remark')
for i, id in enumerate(oracle_id):
stmt = "insert into attendance( oracle_id, name, status, shift, remark) VALUES(%s, %s, %s, %s, %s)"
cur.executemany(stmt, (id,oracle_id[i], name[i], status[i], remark[i]))
cur.commit()
return 'That is success'
return render_template('take_attendance.html')
The funny part is once or twice i found the data in my table while testing, but after wards nothing goes there. Is there any error i made here?
The HTML form i used is
<form action="{{ url_for('submit') }}" method="POST" name="attendance">
<table cellpadding="2" width="20%" bgcolor="#F7F7F7" align="center" cellspacing="10">
<tr>
<td colspan=2>
<center><font size=4><p>Attendance</p></font></center>
</td>
</tr>
<tr>
<td align="center">ID</td>
<td align="center">Name</td>
<td align="center">Status</td>
<td align="center">Remark</td>
</tr>
{% for data in userDetails %}
<tr>
<td><input type="text" name="oracle_id" id="oracle_id" size="6" value="{{data.oracle_id}}"></td>
<td><input type="text" name="name" id="name" size="20" value="{{data.name}}"></td>
<td>
<select name="status">
<option value="-1">select..</option>
<option value="A">1130</option>
<option value="W" selected>1122</option>
</select></td>
<td><textarea rows="1" cols="20" name="remark"></textarea></td>
</tr>
{% endfor %}
<tr>
<td>
<input type="reset">
</td>
<td colspan="2">
<input type="submit" value="Submit">
</td>
</tr>
</table>
</form>
I was trying for over a week but nothing changed. Thanks in advance for your effort.
Execute many is used if you prepare a sql statement without data and feed it multiple rows of values - you feed it one tuple, not a list of tuples.
#app.route('/submit', methods=['GET','POST'])
def submit():
if request.method == 'POST':
cur = connection.cursor()
userDetails = request.form
oracle_id = userDetails.getlist('id')
name = userDetails.getlist('name')
status = userDetails.getlist('status')
remark = userDetails.getlist('remark')
# marry the right data:
data = list(zip(range(len(oracle_id)),oracle_id,name,status,remark))
# range(len(oracle_id)) delivers the same ids as your code does
# wich is most probably **wrong** on many levels...
stmt = "insert into attendance( oracle_id, name, status, shift, remark) VALUES(%s, %s, %s, %s, %s)"
cur.executemany(stmt, data) # provide the list of rows to execute many
cur.commit()
return 'That is success'
return render_template('take_attendance.html')
That said, its probably incorrect - you insert as id the index gathered from enumerating(oracle_id) - which will always start at 0 for each new iteration, so you are inserting the same id over different calls to def submit().
Use How to debug small programs to debug your code.

Categories

Resources