Cannot get HTML to display SQLite3 data with python & flask - python

I'm having an issue getting an HTML page to display my SQLite3 data using Python & Flask. I found a question on here and used the same code, plus different variations to no success. There are no error messages and the HTML page loads, however there is no data present. This is the code I am using to get the data;
#app.route("/viewpackages", methods=['GET'])
def viewpackages():
con = sqlite3.connect('utpg.db')
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson,"
"shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
return render_template("view_packages.html", items=getpackages.fetchall())
this is the code I attempting to use to display the data;
<table>
{% for item in items %}
<tr>
<td>{{column1}}</td>
<td>{{column2}}</td>
<td>{{column3}}</td>
<td>{{column4}}</td>
<td>{{column5}}</td>
<td>{{column6}}</td>
<td>{{column7}}</td>
<td>{{column8}}</td>
</tr>
{% endfor %}
</table>
I tried changing 'column' to the actual db column name, with the same issue. I tried calling SELECT * instead of each individual column, same issue. If I run this code in python;
con = sqlite3.connect('utpg.db')
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson, shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
packages = getpackages.fetchall()
for row in packages:
print(row)
It returns the desired results. So I am thinking there is an issue with the HTML somewhere but I cannot figure it out.

Please try the following code and let me know if it works for you:
<table>
{% for item in items %}
<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>
</tr>
{% endfor %}
</table>
Test with the following code:
app.py
from flask import Flask, render_template
import sqlite3
app = Flask(__name__)
app.secret_key = 'development key'
#app.route('/users')
def get_users():
con = sqlite3.connect('mydb.db')
db = con.cursor()
db.execute('insert into user values ("Aaa", "AAA")')
db.execute('insert into user values ("Bbb", "BBB")')
res = db.execute('select * from user')
return render_template('users.html', users=res.fetchall())
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
templates/users.html
<html !DOCTYPE>
<head>
<title>SQLite</title>
</head>
<body>
<table>
{% for user in users %}
<tr>
<td>{{ user[0] }}</td>
<td>{{ user[1] }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>

Here is what I had to do.. For anyone else having this issue, I'm not sure why but Jinja did not want to let me access by index so I did..
#app.route("/viewpackages", methods=['GET'])
def viewpackages():
con = sqlite3.connect('utpg.db')
con.row_factory = sqlite3.Row
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson,"
"shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
return render_template("view_packages.html", items=getpackages.fetchall())
and change the HTML to..
<table>
{% for col in items %}
<tr>
<td>{{ col['pck_id'] }}</td>
<td>{{ col['client_id'] }}</td>
<td>{{ col['date'] }}</td>
<td>{{ col['price'] }}</td>
<td>{{ col['privatelesson'] }}</td>
<td>{{ col['shortgamelesson'] }}</td>
<td>{{ col['playinglesson'] }}</td>
<td>{{ col['notes'] }}</td>
</tr>
{% endfor %}
</table>
All working now, thank for pointing me in the right direction!

Related

How to delete table content from sqlite Django

I want to delete the data when pressing the trash bin button. I am able to submit, edit petty cash into the database. I am only left with deleting the data.
This is my views.py
def deleteclaims(request, id):
context = initialize_context(request)
user = context['user']
#get id of particular form.
claims = SaveClaimForm.objects.get(id=id)
if request.method == 'POST':
claims.name = request.POST['name']
claims.email = request.POST['email']
claims.claim = request.POST['claim']
claims.claimtype = request.POST.get('claimtype')
claims.description = request.POST['description']
claims.receipt = request.FILES['receipt']
claims.cheque = request.POST.get('Cheque')
claims.status = request.POST['status']
claims.delete()
claims.save()
return render(request, 'Login/existingclaims.html', {'claims':claims, 'user':user}, {'action' : 'Delete claims'})
In my html
<tr align="center">
<td>{{ claims.id }}</td>
<td>{{ claims.name }}</td>
<td>{{ claims.email }}</td>
<td>{{ claims.claim }}</td>
<td>{{ claims.claimtype }}</td>
<td>{{ claims.description }}</td>
<td> Click to View </td>
<td>{{ claims.cheque }}</td>
<td>{{ claims.status }}</td>
<td><i class="fas fa-pencil-alt"></i></td>
<td><i class="fas fa-trash"></i></td>
</tr>

Fetching and display the data in a Django Template Using MYSQL RAW SQL QUERY

Here is my Django Template Used to Display The data in table Format...
enter code here
<table class="content" border="2px">
<thead>
<tr>
<th>S-No</th>
<th>Name</th>
<th>Email</th>
<th>Productname</th>
<th>Quantity</th>
<th>Price</th>
<th>Ordertime</th>
<th>Orderstatus</th>
<th>Actions</th>
</tr></thead>
<tbody>
{% for row in records %}
<tr align="center">
<td>{{row.pid}}</td>
<td>{{ row.username }}</td>
<td>{{ row.email }}</td>
<td>{{ row.productname }}</td>
<td>{{ row.quantity }}</td>
<td>{{ row.price }}</td>
<td>{{ row.ordertime }}</td>
<td>{{ row.orderstatus }}</td>
<td><input type="submit" value="Accept"> <input type="button" value="Reject"></td>
</tr>
{% endfor %}
</tbody>
</table>
And This is my Views.py Page for the fetching up of the data
def viewpro(request):
con = mysql.connector.connect(user='root', password='', host='localhost', database='company1')
cur = con.cursor()
cur.execute("SELECT * FROM user_order")
records=cur.fetchall()
print(records)
con.commit()
cur.close()
con.close()
#context = {'viewpro' : user_order.objects.all()}
return render(request, "viewpro.html", {'records':records})
But Here The problem is it display the no.of table rows same like DB(It have 4 records and table shows 4 rows But no data in the fields).....Pls Help me to get rid of that....Only using raw queries....

can't make index function work in cs50 finance

I am completely stuck in making index function work in cs50 finance! This function should return in a html page a table with the details of the transactions made online (details are saved in a database). But it's not working: even if there is a transaction in my database, my function doesn't find it, the table is empty.
this is my code:
def index():
"""Show portfolio of stocks"""
rows = db.execute("SELECT symbol, price, shares FROM transactions WHERE id = :user_id", user_id=session["user_id"])
transactions_info = []
total_worth = 0
for transaction_info in rows:
symbol = rows [0]["symbol"]
shares = rows [0]["shares"]
price = lookup(symbol)
worth = shares * price ["price"]
total_worth += worth
transactions_info.append(transaction_info)
return render_template("index.html", rows=rows, transactions_info=transactions_info)
And this is my HTML page:
{% extends "layout.html" %}
{% block title %}
Index
{% endblock %}
{% block main %}
<table class="table table-striped" style="width:100%">
<tr>
<th>Symbol</th>
<th>Company</th>
<th>Shares</th>
<th>Price</th>
<th>TOTAL</th>
</tr>
{% for transaction in transactions %}
<tr>
<td>{{ transaction_info.symbol }}</td>
<td>{{ transaction_info.name }}</td>
<td>{{ transaction_info.shares }}</td>
<td>{{ transaction_info.price }}</td>
<td>{{ transaction_info.worth }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Thanks for your help!
In index() you are sending a list called transactions_info here
return render_template("index.html", rows=rows, transactions_info=transactions_info)
In the html you are looping over a list called transactions here {% for transaction in transactions %}.

How to pass certain key and value of a python dictionary to HTML script

I am using flask and in one endpoint I just pass the following dictionary to html file:
app = Flask(__name__)
#app.route("/home")
def home():
q = {"id":23,
"path": '/usr/test.py',
"mynum": 22}
return render_template("home.html", query=q)
in HTML file:
{% for value in query.values() %}
<td>{{ value }}</td>
{% endfor %}
But in this way I am passing all the key-value's but I need to pass certain key-values. More clear, I expect such a solution in HTML if exist:
<td>{{ query["path"] }}</td>
<td>{{ query["id"] }}</td>
<td>{{ query["mynum"] }}</td>
I also tried this:
<td>{{ query.path }}</td>
<td>{{ query.id }}</td>
<td>{{ query.mynum }}</td>
but prints query.path, query.id , query.mynum rather than values
Printing dictionary specific key's value in Jinja2 template without loop
If you want to print specific key of a dictionary, you may use .get() method.
app.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/home")
def home():
q = {"id":23,"path": '/usr/test.py',"mynum": 22}
return render_template("home.html", query=q)
home.html:
<table>
<tr>
<th>ID</th>
<th>Path</th>
<th>Number</th>
</tr>
<tr>
<td>{{ query.get("id") }}</td>
<td>{{ query.get("path") }}</td>
<td>{{ query.get("mynum") }}</td>
</tr>
</table>
Output:
If the key is not found in the dictionary it will print None as value. You may also pass default value as second parameter of the get method.
E.g.:
{{ query.get("arsho", "Value not found") }}
It looks like the issue you are dealing with is that the order of the key/values in the dictionary is not the same order that you would like to display. Instead of hard-coding the <td> elements, you can create a list of the keys in the order you want them to appear and pass that to the template.
import jinja2
query = {"id":23,
"path": '/usr/test.py',
"mynum": 22}
ordered_keys = ('path', 'id', 'mynum')
h = '''<table><tr>
{% for k in ordered_keys -%}
<td>{{ query.get(k, '') }}</td>
{% endfor -%}
</tr></table>
'''
t = jinja2.Template(h)
print(
t.render(query=query, ordered_keys=ordered_keys)
)
# prints:
<table><tr>
<td>/usr/test.py</td>
<td>23</td>
<td>22</td>
</tr></table>

Creating an HTML table with database values in Flask

I want to display a table showing the values of three fields for each of the units in a table. Some assistance with creating the dictionary from the database and passing objects to the template would be greatly appreciated.
#app.route('/')
def index(row):
unit_count = Units.query.count()
unit = Units.query.filter_by(id=row).first()
rows = [] # Unsure how to define rows from Units db table
return render_template('table_overview.html', title='Overview', rows=rows, unit=unit)
{% for row in rows %}
<tr>
<td>{{ row.unit.idnum }}</a></td>
<td>{{ row.unit.product_code }}</td>
<td bgcolor="{{ row.unit.stat_colour }}">{{ row.unit.unit_status }}</td>
</tr>
{% endfor %}
First off your view function can't receive the row input you specify. If you're trying to show all rows in the table you can do it like this:
views.py:
#app.route('/')
def index():
rows = Units.query.all()
return render_template('table_overview.html',
title='Overview',
rows=rows)
table_overview.html (template)
{% for row in rows %}
<tr>
<td>{{ row.idnum }}</a></td>
<td>{{ row.product_code }}</td>
<td bgcolor="{{ row.stat_colour }}">{{ row.unit_status }}</td>
</tr>
{% endfor %}

Categories