i have database for example
id
account_id
date
1
127
2022-04-25
2
128
2022-04-25
3
127
2022-04-24
4
128
2022-04-24
And i need separate this on 2 different tables:
account_id
date header
127
2022-04-25
127
2022-04-24
and the same with 128
That's my code for 1 table and i don't know how to separate
#bp.route('/')
def main():
wcms = Wcm.query.order_by(Wcm.date.desc()).all()
return render_template('table.html', wcms=wcms)
HTML:
<table class="table table-hover table-dark wcm">
<thead>
<tr>
<th>Date</th>
<th>WCM account ID</th>
<th>Number of standard tags</th>
<th>Number of extended tags</th>
</tr>
</thead>
<tbody>
{% for wcm in wcms %}
<tr>
<td>{{ wcm.date }}</td>
<td>{{ wcm.account_id }}</td>
<td>{{ wcm.nbm_stardart_tags }}</td>
<td>{{ wcm.nbm_custom_tags }}</td>
</tr>
{% endfor %}
</tbody>
</table>
For the following code to work we need to sort the data by the grouping value first. Since you want to seperate account IDs, I chose ASC.
wcms = Wcm.query.order_by(Wcm.account_id.asc(), Wcm.date.desc()).all()
The lambda returns the account ID to collect all entries into one list. groupby returns a list of tuples, the list() call is needed to evaluate the lazy iterator creating the group. The outer list comprehensions creates a list of those grouped Wcm lists.
wcms_by_account = [
list(wcm_group)
for acc_id, wcm_group
in groupby(wcms, lambda x: x.account_id
]
List strucure:
[
[
Wcm(account_id=127, date=2022-04-25, ...),
Wcm(account_id=127, date=2022-04-24, ...),
],
[
Wcm(account_id=128, date=2022-04-25, ...),
Wcm(account_id=128, date=2022-04-24, ...),
],
...
]
Then change your Web Template to handle a list of lists, creating a new table for each inner list.
{% for wcms in wcms_by_account %}
<table class="table table-hover table-dark wcm">
<thead>
<tr>
<th>Date</th>
<th>WCM account ID</th>
<th>Number of standard tags</th>
<th>Number of extended tags</th>
</tr>
</thead>
<tbody>
{% for wcm in wcms %}
<tr>
<td>{{ wcm.date }}</td>
<td>{{ wcm.account_id }}</td>
<td>{{ wcm.nbm_stardart_tags }}</td>
<td>{{ wcm.nbm_custom_tags }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
Related
I am developing a Django application about statistics calculations. But now I have faced a problem that I can't solve. I have two lists in my views.py list1 = [5, 6, 7, 8] list2 = [5, 6, 7, 8]. I sent this to Django templates and I also sent 'n' : range(7) as context.
In my html code, there have a code
<table>
<thead>
<tr>
<th>list1</th>
<th>list2</th>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</thead>
</table>
Now I want to print first value of each list in first row, then second value of each list in second row and so on.
So I have made a code something like this
<table>
<thead>
<tr>
<th>list1</th>
<th>list2</th>
</tr>
{% for i in n %}
<tr>
<td> {{ list1.i }} </td>
<td>{{ list2.i }}</td>
</tr>
{% endfor %}
</thead>
</table>
After writting this code, I am not getting any error but the values are not showing. Instead a blank row and columns are being made.
Please help me to print the values that I want to print.
As a general rule, you should keep all the logic on views.
What I'd do is zip the lists and use tuples instead.
views.py:
new_list = zip(list1, list2)
context = {
'new_list': mylist,
}
and on templates:
{% for list1_item, list2_item in new_list %}
<tr>
<td> {{ list1_item }} </td>
<td> {{ list2_item }}</td>
</tr>
{% endfor %}
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 am trying to display data on my web app from a CSV file using Flask. The below code reads my CSV file and assigns stocklist as the variable for my data. In the HTML code below it, using jinga logic, I iterate through stocklist however my CSV columns are returned as rows (see sample output and pic). How do I display the rows correctly?
My python function:
#app.route('/stocks')
def Stocks():
filename = 'stock_scraper - dev.csv'
data = pandas.read_csv(filename, header=0)
stocklist = list(data.values.flatten())
return render_template('stocks.html', stocklist=stocklist)
My web app for iterating through stocklist:
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Ticker</th>
<th>Closing Price</th>
<th>Closing Date</th>
</tr>
</thead>
<tbody>
{% for eachstocks in stocklist%}
<tr>
<td>{{ eachstocks }}</td>
<td>{{ eachstocks }}</td>
<td>{{ eachstocks }}</td>
<td>{{ eachstocks }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Output:
Haks, i removed the nested loop and added the list position in each value to fix it. Works now.
<tbody>
{% for value in stocklist %}
<tr>
<td>{{ value[0] }}</td>
<td>{{ value[1] }}</td>
<td>{{ value[2] }}</td>
<td>{{ value[3] }}</td>
</tr>
{% endfor %}
</tbody>
output
enter image description here
You shouldn't flatten the list.
Try this:
#app.route('/stocks')
def Stocks():
filename = 'stock_scraper - dev.csv'
data = pandas.read_csv(filename, header=0)
stocklist = list(data.values)
return render_template('stocks.html', stocklist=stocklist)
Then for the Jinja template:
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Ticker</th>
<th>Closing Price</th>
<th>Closing Date</th>
</tr>
</thead>
<tbody>
{% for value in stocklist%}
<tr>
<td>{{ value[0] }}</td>
<td>{{ value[1] }}</td>
<td>{{ value[2] }}</td>
<td>{{ value[3] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I have this problem where I can't display the contents of a dictionary into a webpage.
web_indiv[url_sequence] = {'url' : converted_url , 'name' : x.name, 'count' : web_count_current }
return render_template('video.html', web_data = web_indiv)
The web_indiv is populated using a loop, and then passed to video.html as web_data.
Sample dictionary
{1: {'url': 'http://www.drpeppersnapplegroup.com/', 'name': 'Dr. Pepper-Snapple Group', 'count': 57}, 2: {'url': 'http://www.rccolainternational.com/', 'name': 'Royal Crown Cola', 'count': 41}}
Note: It is a dictionary that contains another dictionary inside it.
This is what I already have on my html file.
{% for key1,line in web_data.items() %}
{% for key2,line_item in line.items() %}
<tr>
<td class="col-md-2">{{ line_item['url'] }}</td>
<td class="col-md-2">{{ line_item['name'] }}</td>
<td class="col-md-2">{{ line_item['count'] }}</td>
</tr>
{% endfor %}
{% endfor %}
Data won't display on the webpage.
Thank you for taking time to read my query.
If it is just a dict, you could try this:
<html>
{{web_data[url_sequence]}}
<table>
<tr>
{%for value in web_data[url_sequence].values()%}
<td class="col-md-2">{{ value }}</td>
{% endfor %}
</tr>
</table>
</html>
Note that the web_data[url_sequence] is a dictionary.
This one will have the orders (url, name and then count):
<tr>
<td class="col-md-2">{{ web_data[url_sequence].url }}</td>
<td class="col-md-2">{{ web_data[url_sequence].name }}</td>
<td class="col-md-2">{{ web_data[url_sequence].count }}</td>
</tr>
Real example:
Suppose you have the dictionary web_indiv, then you want to render it to template video.html
#app.route('/', methods=['GET'])
def root():
web_indiv = {}
url_sequence = 'test'
web_indiv[url_sequence] = {'url':'testabc','name':'hello','count': 4}
return render_template('video.html', web_data = web_indiv, url_sequence = url_sequence)
Then you can use the dict in template like this:
<tr>
<td class="col-md-2">{{ web_data[url_sequence].url }}</td>
<td class="col-md-2">{{ web_data[url_sequence].name }}</td>
<td class="col-md-2">{{ web_data[url_sequence].count }}</td>
</tr>
The html will show you:
testabc hello 4
{% for key2,line_item in web_data[url_sequence].items %}
<tr>
<td class="col-md-2">{{ line_item }}</td>
</tr>
{% endfor %}
I have given data from views to template in django. I want to iterate these multiple keys to build a html table.
views.py
data={'pacientes':p,'inicios':i,'finales':f,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)
I want to do something like
index.html
<table>
{% for p, i, f in pacientes, inicios, finales %} # I know that this code is not work
<tr>
<td>{{ p.nombre }}</td>
<td>{{ i }}</td>
<td>{{ f }}</td>
<tr>
{% endfor %}
</table>
p is an object from Pacientes
class Usuario(models.Model):
dni=models.CharField(max_length=9,primary_key=True)
clave=models.CharField(max_length=16)
nombre=models.CharField(max_length=30)
...
and i is a string's list as
('20-2-2014', '12-2-2014', ..., '11-5-2014')
I suppose that each index of paciente, inicio and finales are related between them.
Just as Ignacio says, you can write some code in the view, before passing it to the template in order to solve your problem.
A possible solution could be packing the values in a list of tuples like this:
[
(pacientes[0], inicios[0], finales[0]),
(pacientes[1], inicios[1], finales[1]),
...
]
You can achieve this easily by using the zip function in your view:
pacientes_data = zip(p, i, f)
data={'pacientes_data':pacientes_data,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)
And in your template:
<table>
{% for p,i,f in pacientes_data %}
<tr>
<td>{{ p.nombre }}</td>
<td>{{ i }}</td>
<td>{{ f }}</td>
</tr>
{% endfor %}
</table>
Here is a working solution for similar task:
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Model Name</th>
<th scope="col">Device Count</th>
</tr>
</thead>
<tbody>
{% for all_model in all_models %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ all_model.0 }}</td>
<td>{{ all_model.1 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
In view.py
all_models = []
all_models_names = [1,2,3,4]
all_models_names_values = [1,2,3,4]
all_models = zip(all_models_names,all_models_names_values)
return render(request, "sample.html",{'all_models':all_models})