This function is supposed to return a table that resumes all the transactions made grouping them by stock symbol. I'm stuck on this because I keep geting an error that seems to come from sqlite researche (transactions_sql) and more specially from the way I'm calling the user's id. Does someone can explain me what I'm doing wrong ? Did I not create the right link with the foreign key (id) on my transactions database ?
Here is the error message I get : RuntimeError: near "WHERE": syntax error
#app.route("/")
#login_required
def index():
"""Show portfolio of stocks"""
transactions_sql = db.execute("SELECT company_symbol, SUM(shares) FROM transactions GROUP BY company_symbol WHERE id IN (?)", session["user_id"])
index = lookup(transactions_sql.company_symbol)
value = index["price"] * int(transactions_sql.SUM(shares))
cash_sql = db.execute("SELECT cash FROM users WHERE id IN (?)", session["user_id"])
cash_left = float(cash_sql[0]["cash"])
return render_template("index.html", transactions_sql=transactions_sql, index=index, value=value, cash_left=cash_left)
HTML
{% extends "layout.html" %}
{% block title %}
Index
{% endblock %}
{% block main %}
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Symbol</th>
<th scope="col">Name</th>
<th scope="col">Shares</th>
<th scope="col">Current price</th>
<th scope="col">Total value</th>
</tr>
</thead>
<tbody>
{% for transaction in transactions %}
<tr>
<th scope="row">{{ transactions_sql.company_symbol }}</th>
<td>{{ index["name"] }}</td>
<td>{{ transactions_sql.SUM(shares) }}</td>
<td>{{ index["price"] | usd }}</td>
<td>{{ index["value"]| usd }}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td class="border-0 fw-bold text-end" colspan="4">Current cash balance</td>
<td class="border-0 text-end">{{ cash_left | usd }}</td>
</tr>
<tr>
<td class="border-0 fw-bold text-end" colspan="4">TOTAL VALUE</td>
<td class="border-0 w-bold text-end">{{ cash_left | usd }}</td>
</tr>
</tfoot>
</table>
{% endblock %}
And here is my sqlite database :
sqlite> .schema
CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT NOT NULL, hash TEXT NOT NULL, cash NUMERIC NOT NULL DEFAULT 10000.00);
CREATE TABLE sqlite_sequence(name,seq);
CREATE UNIQUE INDEX username ON users (username);
CREATE TABLE transactions(
transaction_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
company_symbol TEXT NOT NULL,
date DATETIME,
shares NUMERIC NOT NULL,
price NUMERIC NOT NULL,
cost NUMERIC NOT NULL,
id INTEGER,
FOREIGN KEY (id)
REFERENCES users (id));
Thanks in advance for your help !
The problem is the syntax of this sql:
SELECT company_symbol, SUM(shares) FROM transactions GROUP BY company_symbol WHERE id IN (?)
A GROUP BY clause comes after the WHERE clause.
Here is the doc for reference.
Related
order_list = Order.objects.filter(
is_deleted=0, order_status__in=[4], order_type=0)
order_list_data = order_list.annotate(
customer_gross_sum=F('invoice__original_amount') -
F('invoice__discount_amount')+F('invoice__tax_amount'),
dcount=Count('user_id'),customer_transactions=F('invoice__transaction_invoice__transaction_amount'))
print(order_list_data.values())
from the table above, the customer_transactions in the queryset is called in the column payment in the table. The second and third in the table is of the same bill with two transactions. Is it possible to bring that under one data.
TEMPLATE
<table id="table">
<thead>
<td class="no-sort">Sl No</td>
<td class="no-sort">BILL DATE</td>
<td class="no-sort">BILL NO</td>
<td>BILL VALUE (Rs)</td>
<td>PAYMENT (Rs)</td>
<td>BALANCE (Rs)</td>
</thead>
{% for data in order_list_data %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{data.invoice.bill_date}}</td>
<td>{{data.invoice.bill_no}}</td>
<td>{{data.customer_gross_sum}}</td>
<td>{{data.customer_transactions}}</td>
<td></td>
</tr>
{% endfor %}
</table>
Expecting an output like
I've seen a few CS50 Finance help questions regarding /index. I'm trying to get the route to display a user's owned stock information (share number, value, price, etc.). Right now it displays the correct share amounts but does not display the name, value, or price (all blank). The "cash" and "grandTotal" amounts display but grandTotal is not the correct amount. I think I'm just confused on how to access specific values in my returns.
Python/sqlite:
def index():
"""Show portfolio of stocks"""
# sql queries to select stock info
user_id = session["user_id"]
stocks = db.execute("SELECT stock, symbol, SUM(shares) AS totalShares FROM purchases WHERE userid == :userid GROUP BY symbol", userid=user_id)
currentCash = db.execute("SELECT cash FROM users WHERE id == :userid", userid=user_id)
# Global variables to be updated
tableInfo = []
grandTotal = currentCash[0]["cash"]
#Grabbing info from each owned stock
for stockInfo in stocks:
symbol = stocks[0]["symbol"]
shares = stocks[0]["totalShares"]
name = stocks[0]["stock"]
currentStock = lookup(symbol)
price = currentStock["price"]
value = price * shares
grandTotal += value
tableInfo.append(stockInfo)
# Display a table with portfolio info for current user
return render_template("index.html", tableInfo=tableInfo, grandTotal=usd(grandTotal), currentCash=usd(currentCash[0]["cash"]))
HTML:
{% extends "layout.html" %}
{% block title %}
Your Portfolio
{% endblock %}
{% block main %}
<table class="table">
<thead>
<tr>
<th scope="col">Stock</th>
<th scope="col">Number of shares</th>
<th scope="col">Current price</th>
<th scope="col">Total value</th>
</tr>
</thead>
<tbody>
{% for stock in tableInfo %}
<tr>
<td>{{ stock.name }}</td>
<td>{{ stock.totalShares }}</td>
<td>{{ stock.price }}</td>
<td>{{ stock.value }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<table class="table">
<thead>
<tr>
<th scope ="col">Cash remaining</th>
<th scope ="col">Grand total</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ currentCash }}</td>
<td> {{ grandTotal }}</td>
</tr>
</tbody>
</table>
{% endblock %}
i want to display my query from SQLite3 into Bootstrap Table. but it seems doesnt work and wont display the table.
herewith my code
views.py
#main.route('/currentlist', methods=["GET"])
def current():
if request.method == 'GET':
Connection = sqlite3.connect('C:\\Backup_old\\Task\\e_ticket\\my_app\\db\\customer.db')
cursor = Connection.cursor()
query2 = "SELECT * from customer"
cursor.execute(query2)
test = cursor.fetchall()
return render_template('overview.html', testform = test)
HTML
<div class= "content">
<table id="dtBasicExample" class="table" width="100%">
<thead>
<tr>
<th class="th-sm">Date
</th>
<th class="th-sm">time
<th class="th-sm">customer
</th>
<th class="th-sm">pic
</th>
<th class="th-sm">category
</th>
<th class="th-sm">description
</th>
</tr>
</thead>
<tbody>
<tr>
<td>9 December 2021</td>
<td>15:30:00</td>
<td>AB Corp.</td>
<td>Bob</td>
<td>network</td>
<td>network is down</td>
</tr>
<tr>
<td>9 December 2021</td>
<td>17:30:00</td>
<td>AB Corp.</td>
<td>Alex</td>
<td>computer</td>
<td>computer is broken</td>
</tr>
<tr>
<td>10 December 2021</td>
<td>05:32:00</td>
<td>CD Corp.</td>
<td>Bob</td>
<td>Server</td>
<td>server is down</td>
</tr>
<tr>
<td>12 December 2021</td>
<td>10:30:00</td>
<td>AB Corp.</td>
<td>Bob</td>
<td>printer</td>
<td>printer is down</td>
</tr>
</tbody>
</table>
</div>
it should be like this but with the data from DB
enter image description here
i've read many similiar question like this, but most of them use SQLAlchemy.
Any help greatly appreciated!
You need to use a loop and template variables with the data.
<tbody>
{% for row in testform %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
<td>{{ row[2] }}</td>
<td>{{ row[3] }}</td>
<td>{{ row[4] }}</td>
<td>{{ row[5] }}</td>
</tr>
{% endfor %}
</tbody>
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....
I am having trouble getting the code to properly display the portfolio in index.html.
My logic with this function is to get a list of all the stocks and cash one user has, and then in a "for" loop, look up the company name and current price for each stock, the total value, and then insert all of that information into a new list of dictionaries (display_portfolio). Then the render_template should display "display_portfolio" with this information, as well as the user's total cash and total value of everything. However, with my current setup, it is displaying the total cash and grand total, but nothing from the individual stocks. I am really not sure why that is, and I am unsure if the issue is in my html or in the flask function itself.
This is the function:
#app.route("/")
#login_required
def index():
"""Show portfolio of stocks"""
# Retrive portfolio
portfolio = db.execute("SELECT symbol, SUM(amount) as amount FROM purchases WHERE id = ? ORDER BY symbol", (session["user_id"]))
user_cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])
cash = user_cash[0]["cash"]
display_portfolio = []
shares_total = 0
# loop through portfolio symbols to access name and share price for each symbol
for row in portfolio:
requested_quote = lookup(row["symbol"])
symbol = row["symbol"]
amount = row["amount"] #shares
price = float(requested_quote["price"])
name = requested_quote["name"]
share_total = (float(amount) * price)
shares_total = shares_total + share_total
display_portfolio.append({'symbol':symbol, 'name':name, 'shares':amount, 'price':price, 'share_total':share_total})
grand_total = shares_total + cash
return render_template("index.html", display_portfolio = display_portfolio, cash = cash, grand_total = grand_total)
This is index.html:
{% extends "layout.html" %}
{% block title %}
Portfolio
{% endblock %}
{% block main %}
<div>
<table class="table table-striped">
<thead>
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Shares</th>
<th>Price</th>
<th>TOTAL</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="3"></td>
<td>TOTAL</td>
<td>{{ grand_total | usd }}</td>
</tr>
</tfoot>
<tbody>
{% for row in display_portfolio %}
<tr>
<td>{{ display_portfolio.symbol }}</td>
<td>{{ display_portfolio.name }}</td>
<td>{{ display_portfolio.shares }}</td>
<td>{{ display_portfolio.price }}</td>
<td>{{ display_portfolio.total }}</td>
</tr>
{% endfor %}
<td colspan="3"></td>
<td>Cash</td>
<td>{{ cash | usd }}</td>
</tbody>
</table>
</div>
{% endblock %}
I should also note, that when I add "| usd" to "display_portfolio.price" in that it reads:
<td>{{ display_portfolio.price | usd }}</td>
I am also getting a completely separate error, and not sure why it would work with cash and not this.
I can confirm that there exists purchases in the sql database the "portfolio" variable is retrieving.
This is what it looks like:
Display
Any help will be appreciated, thanks!
From MDN doc on tfoot:
Permitted parents: A <table> element. The <tfoot> must appear after
any <caption>, <colgroup>, <thead>, <tbody>, or <tr> element. Note
that this is the requirement as of HTML5.
Suspect the Cash line is displayed because it is missing <tr> tags.
Nu HTML Validator from W3C is your friend :)