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.
Related
<table style="width:100%", border="1">
{% for item in items %}
<tr>
<td>{{Description[item]}}</td>
<td>{{Location[item]}}</td>
<td>{{Status[item]}}</td>
</tr>
{% endfor %}
</table>
I am trying to create a table using this for loop, the variables are being passed through in the flask framework, 'items' will always be the same length as the three lists (Description, location and status).
I am aware of the question below:
How to build up a HTML table with a simple for loop in Jinja2?
but I can not see how my code here differs to the working answer to this question, is it because I am using a list instead of a dictionary ?
This is the flask framework, where the lists
are created an passed through using render template:
def index():
description = []
location = []
status = []
imix80m = ''
imix = ''
with open('behavepretty.json') as a:
data = json.load(a)
for n in range(0,len(data)):
i = 0
for i in range(0, len(data[n]['elements'])):
x = data[n]['elements'][i]['name']
description.append(x)
y = data[n]['elements'][i]['location']
location.append(y)
z = data[n]['elements'][i]['status']
status.append(z)
n = 0
for n in range(0,len(data)):
if n == 0:
imix80m = data[n]['status']
elif n == 1:
imix = data[n]['status']
a.close()
return render_template('trial.html', Description = description, Location= location, Status = status, result1 = imix80m, result2 = imix, jfile = data, items = description)
You just need a loop counter:
<table style="width:100%", border="1">
{% for item in Description %}
<tr>
<td>{{Description[loop.index0 ]}}</td>
<td>{{Location[loop.index0]}}</td>
<td>{{Status[loop.index0]}}</td>
</tr>
{% endfor %}
</table>
Or, you could pack the 3 into a list of lists:
my_list = [[Description0, Location0, Status0], [Description1, Location1, Status1], ...]
Then:
{% for item in my_list %}
<tr>
<td>{{ item[0] }}</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
</tr>
{% endfor %}
Or, more robustly, a list of dictionaries:
my_list = [
{
"description" : xxx,
"location" : yyy,
"status" : zzz
},
{
"description" : www,
"location" : eee,
"status" : rrr
},
...
]
Then:
{% for item in my_list %}
<tr>
<td>{{ item.description }}</td>
<td>{{ item.location }}</td>
<td>{{ item.status }}</td>
</tr>
{% endfor %}
My Django View:
def hub(request):
context = {}
hub_id = [value['id'] for value in hub_data['data']]
hub_name = [value['attributes']['name'] for value in hub_data['data']]
hub_url = [value['links']['self']['href'] for value in hub_data['data']]
nested_dict = dict(zip(hub_name, map(list, zip(hub_id, hub_url))))
context ['rows'] = nested_dict
return render(request, 'connector/hub.html', context)
The context['rows'] results in:
{'rows': {hub_name1 : ['hub_id1', 'hub_url1'],{hub_name2 : ['hub_id2', 'hub_url2'], etc.. }
I am trying to pass it a HTML table that looks like this:
<th scope="col">Hub Name</th>
<th scope="col">Hub ID</th>
<th scope="col">Hub URL</th>
My tablebody looks like this:
<tbody>
{% for key, value in rows.items %}
<tr>
<td> {{ key }}</td>
<td> {{ value }}</td> **//how do i just get hub_id here**
<td> Don't know what to do here to get: hub_url </td>
</tr>
{% endfor %}
</tbody>
But I want to add another -tag to fill with hub_url. How do I extract the hub_id data and add it to the column: Hub ID and extract the hub_url and add it to the column Hub URL.
Any help would be much appreciated!
You can pass the data to the template without transforming it
return render(request, 'connector/hub.html', {'data': hub_data['data']})
And then lookup the attributes using the "dot" template syntax for each row
<tbody>
{% for row in data %}
<tr>
<td>{{ row.attributes.name }}</td>
<td>{{ row.id }}</td>
<td>{{ row.links.self.href }}</td>
</tr>
{% endfor %}
</tbody>
I want to search title with database record. Database record may contain sub-string in many cell which i want to search. I want to render all the records but could not shows because "TypeError: 'Store' object is not iterable" occurs.
My application.py is:
def bookresult():
isbn = request.form.get("isbn")
title = request.form.get("title")
author = request.form.get("author")
year = request.form.get("year")
submit = []
session = Session()
result = session.query(Store).all()
for result in result:
if title in result.title:
return render_template("bookresult.html",results=result)
return render_template("login.html", message="Not found")
session.commit()
And my bookresult.html is:
{% block body %}
<h1> Search result book </h1>
<table>
<tr>
<th> ISBN number </th>
<th> Book title </th>
<th> Author name </th>
<th> Publish year </th>
</tr>
<tr>
{% for result in results %}
<td> {{ result.isbn }} </td>
<td> {{ result.title }} </td>
<td> {{ result.author }} </td>
<td> {{ result.year }} </td>
{% endfor %}
</tr>
</table>
{% endblock %}
Above code works if for loop in html file is removed. But how to get all the records without making iteration in html file.
How to get records iteratively in html file if my search string matched with database cell ?
Issue occurs in
a) if .. is .. True syntax
b) rendering in templates doesn't iterate over and over. You have to pass at once.
c) {% for i in range(count) %} will cause iteration for int object i.e we can access elements of list as list[i] only.
Now application.py will look like:
#app.route("/bookresult", methods=['POST'])
def bookresult():
isbn = request.form.get("isbn")
title = request.form.get("title")
author = request.form.get("author")
year = request.form.get("year")
session = Session()
list1 = []
list2 = []
list3 = []
list4 = []
results = session.query(Store).all()
# return render_template("message.html",result=type(results))
for i in results:
if (title in i.title) is True:
list1.append(i.isbn)
list2.append(i.title)
list3.append(i.author)
list4.append(i.year)
# counter = counter + 1
# else:
# counter = counter + 1
# if (title in i) is True:
# return render_template("bookresult.html",results=i)
# counter = counter + 1
# else:
# counter = counter + 1
# return render_template("bookresult.html", results=list1, list2, list3, list4)
return render_template("bookresult.html", count=len(list1), result1=list1, result2=list2, result3= list3, result4= list4)
session.commit()
And bookresult.html will be:
{% for i in range(count) %}
<tr>
<td> {{ result1[i] }} </td>
<td> {{ result2[i] }} </td>
<td> {{ result3[i] }} </td>
<td> {{ result4[i] }} </td>
</tr>
{% endfor %}
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.
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>