Skip first row when rendering table data with Jinja - python

I have a list representing rows of data. The first item in the list is the column names. When I render the rows using Jinja, I don't want to render the column names, because generating a url for that makes no sense. How can I skip the first row while rendering?
array = [
['one','two','three'],
[0,12,13],
[1,22,16],
[5,66,21],
[2,55,44]
]
#app.route('/')
def index():
return render_template('test.html', table=array)
{% for item in table %}
<tr>
<td>{{ item[0] }}</a></td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
</tr>
{% endfor %}

if all you want is for the template to skip the 1st entry in the array, simply pass to it the appropriate slice of your array, i.e.:
return render_template('test.html', table=array[1:])

Related

creating flask table from data

I'm being trying to put data into a table in flask but its creating a new row for each character for some reason instead of just putting the full string into the row.
code:
#app.route('/')
def logs():
output = ''
try:
conn = redis.StrictRedis(host='redis', port=6379)
for key in conn.scan_iter("log.g*"):
value = str(conn.get(key))
output += "str(key)+ '--' + value"
return render_template('view.html', data=output)
table code:
<table>
{% for row in data %}
<tr>
{% for value in row %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Well, the thing is that your output / data is absolutely unstructured - it is just one big string. You want to make for example a list:
output = []
conn = redis.StrictRedis(host='redis', port=6379)
for key in conn.scan_iter("log.g*"):
value = str(conn.get(key))
output.append("str(key)+ '--' + value")
return render_template('view.html', data=output)
(In your code your return statement is inside the cycle, which means that the cycle will run just once.
The code above will create a list and then the template:
<table>
{% for value in data %}
<tr>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
will print each list member into a table cell. Aside of that, we cannot tell what you want to have in one table row.

Cant Turn Tuple Into String

I am struggling to display two columns (resultlist) in seperate columns. Right now when i return result list its showing in a tuple. When i try to index the for loop(to remove the tuple) with i[0] in the HTML file but i get the first character which is the "("
current output:
column1
('123456', '150.92')
('49815', '70.43')
('19971', '39.35')
If i try to index the for loop in html, current output:
column1
(
(
(
expected output:
Column1 Column2
123456 150.92
49815 70.43
19971 39.35
Current python file:
def subtractboth(alloclist, statementlist):
resultlist = []
for i, j in zip(statementlist, alloclist):
if i[0] == j[0]:
results = float(j[1]) - float(i[1])
if results >= 0:
results = i[0], "{:.2f}".format(results)
print(" ".join(results))
resultlist.append(str(results))
return resultlist
#app.route('/results', methods=['GET', 'POST'])
def main():
connect()
masteracct = request.args.get('masteracct')
cashdt = request.args.get('cashdt')
billdt = request.args.get('billdt')
allocation(connect(), cashdt, masteracct)
statement(connect(), billdt, masteracct)
a = subtractboth(statement(connect(), billdt, masteracct), allocation(connect(), cashdt,
masteracct))
html = render_template('test_results.html', a=a)
return html
HTML:
<table>
<th>Column 1</th>
<th> Column 2</th>
{% for i in a %}
<tr>
<td>{{i}}</td>
<td>{{i}}</td>
</tr>
{% endfor %}
</table>
The Jinja2 template for displaying a table with 2 columns should look like this:
<table>
<tr>
<th>column1</th>
<th>column2</th>
</tr>
{% for v1, v2 in a %}
<tr>
<td>{{ v1 }}</td>
<td>{{ v2 }}</td>
</tr>
{% endfor %}
</table>
The variable a should be a sequence of pairs.

Flask: How do you access group by sum and counts in jinja2?

I am trying to get the values for a query:
total_sales = (Model.query
.with_entities(Model.dept_name,
sa.func.sum(Model.sales),
sa.func.count(Model.sales))
.filter(Model.companyid == companyid)
.filter(Model.sales> 0)
.group_by(Model.companyid, Model.dept_name)
.all())
In my jinja code I have:
{% for item in total_sales %}
<tr>
<td>{{ item.dept_name}}</td>
</tr>
<tr>
<td>{{ item.sum }}</td>
</tr>
<tr>
<td>{{ item.count }}</td>
</tr>
{% endfor %}
The dept_name shows up but the item.sum isn't showing and the item.count shows up as <built-in method count of result object at 0x000002DEA910D098>
If I print(total_sales) I can see the results of the query as a list of tuples. How do I access this in my jinja file?
You need to add labels to the function results so you can access them more clearly. Since you are using count and sum in the template, it'd be like:
sa.func.sum(Model.sales).label('sum'),
sa.func.count(Model.sales).label('count')

Best way to store data(table) and easy acces to represent it

I'm working with the django framework and I found a way to store the data that I recieved by a RPC call. This data follow the JSON format:
{"header":["data_enviament","nom_auditor","matricula","bastidor"],"data":[{"data_enviament":"05/1/2014","nom_auditor":"Brutus Brutus, Marc","matricula":"1234FRX","bastidor":"192891478kjhda"},{"data_enviament":"05/2/2014","nom_auditor":"Pepito Rudolf, Margarita","matricula":"2234FRX","bastidor":"192891478kjhda"},{"data_enviament":"05/5/2014","nom_auditor":"Patrick Linda, Judith","matricula":"5234FRX","bastidor":"192891478kjhda"}],"count":2}
And I store this data into a matrix( at the controller point ), the code is:
for i in range(len(tabla['header'])):
array[0][i] = tabla['header'][i]
x = 1
for data in tabla['data']:
for i in range(len(tabla['header'])):
array[x][i] = data[array[0][i]]
x = x + 1
Then I parse this data by the render function to the template and represent into a html table.
I'm doing fine or there are maybe another way to do it better?
You can transform the data into a list of lists keeping the order of the items according to the header.
Demo from the shell:
>>> from django.template import Template, Context
>>> data = {"header":["data_enviament","nom_auditor","matricula","bastidor"],"data":[{"data_enviament":"05/1/2014","nom_auditor":"Brutus Brutus, Marc","matricula":"1234FRX","bastidor":"192891478kjhda"},{"data_enviament":"05/2/2014","nom_auditor":"Pepito Rudolf, Margarita","matricula":"2234FRX","bastidor":"192891478kjhda"},{"data_enviament":"05/5/2014","nom_auditor":"Patrick Linda, Judith","matricula":"5234FRX","bastidor":"192891478kjhda"}],"count":2}
>>>
>>> data = [[item[header] for header in data['header']] for item in data['data']]
>>> c = Context({'data': data})
>>> template = """
<table>
{% for row in data %}
<tr>
{% for item in row %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
"""
>>> t = Template(template)
>>> print t.render(c)
<table>
<tr>
<td>05/1/2014</td>
<td>Brutus Brutus, Marc</td>
<td>1234FRX</td>
<td>192891478kjhda</td>
</tr>
<tr>
<td>05/2/2014</td>
<td>Pepito Rudolf, Margarita</td>
<td>2234FRX</td>
<td>192891478kjhda</td>
</tr>
<tr>
<td>05/5/2014</td>
<td>Patrick Linda, Judith</td>
<td>5234FRX</td>
<td>192891478kjhda</td>
</tr>
</table>

using list index lookup within a template loop in django

Basically, what I want to do is have the template system loop through two independent lists to fill two columns of a table. My approach was to use an index list (numList) as a way to access the same index of the two lists. I tried using the dot notation for list index lookup within a template loop but it doesn't seem to work in the loop. Any ideas on how I can remedy this?
numList = [0, 1, 2, 3]
placeList = ['park', 'store', 'home', 'school']
speakerList = ['bill', 'john', 'jake', 'tony']
<table>
<tr>
<th>Location</th>
<th>Time</th>
<th>Speaker</th>
</tr>
{% for num in numList %}
<tr>
<td>{{ placeList.num }}</td>
<td>1:30</td>
<td>{{ speakerList.num }}</td>
</tr>
{% endfor %}
</table>
The easiest thing is probably to combine your lists in python and then just look through the combined list in the template:
combinedList = [(placeList[i],speakerList[i]) for i in range(4)]
{% for entry in combinedList %}
<tr>
<td>{{ entry.0 }}</td>
<td>1:30</td>
<td>{{ entry.1 }}</td>
</tr>
{% endfor %}
Or for transparency, you could make combinedList a list of objects or dictionaries for example:
combinedList = [{'place':placeList[i],'speaker':speakerList[i]} for i in range(4)]
{% for entry in combinedList %}
<tr>
<td>{{ entry.place }}</td>
<td>1:30</td>
<td>{{ entry.speaker }}</td>
</tr>
{% endfor %}
You could aggregate these two lists in one.
For example:
yourlist = [('park','bill'),('store','john'),('home','jake'),...]

Categories

Resources