using list index lookup within a template loop in django - python

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'),...]

Related

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')

jinja2: building table by iterating down columns instead of across rows

If I have the following lists:
headers = ['Name', 'Age']
rows = [['Johnny', 30], ['Zack', 20]]
I can easily make a table via Jinja2 (https://jsfiddle.net/equbh9du/1/):
<table class="table table-bordered table-hover">
<thead>
<tr>
{% for h in headers %}
<td>{{ h }}</td>
{% endfor %
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
{% for item in row %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
I'm noticing it's much easier (and more organized) to return my data as a dictionary:
d = {'Name': ['Johnny', 'Zack'], 'Age': [30, 20]}
Is there an easy way to build the table I built above using this dict. I imagine I need to finish the iteration down each column before continuing to the next column (in the example above I finish the iteration across each row before continuing to the next row).
This is the code I have so far but I'm getting a messed up table (https://jsfiddle.net/j164fqy9/1/):
<table class="table table-bordered table-hover">
<thead>
<tr>
{% for h in d %}
<td>{{ h }}</td>
{% endfor %
</tr>
</thead>
<tbody>
{% for h, col_values in d.items() %}
{% for item in col_values %}
<tr>
<td>{{ item }}</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
EDIT: If HTML standard prevents iterating down columns first, then I need to construct the headers and rows from d. Is below the best way to do this?
headers = [h for h in d]
rows = [[l[i] for h, l in d.items()] for i in range(len(d['Name']))]
If you allways have the same number of items in col_values this should work fine :
{% for i in range(d['Name']|count) %}
<tr>
{% for k in d %}
<td>{{ d[k][i] }}</td>
{% endfor %}
</tr>
{% endfor %}

How do I input values from Python lists into an HTML table?

I have two lists in python that I would like to input into two separate columns in an HTML table. What would the code look like on the python end of things and what would it look like for html?
This is what I have in python now:
giver = []
recipient = []
giver.append(name)
recipient.append(match)
return render_template("created.html", givers=givers, recpients=recipients)
And this is what I have in HTML:
<table>
<thead>
<tr>
<th>Giver</th>
<th>Recipient</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ givers }}</td>
<td>{{ recipients }}</td>
</tr>
</tbody>
</table>
Create one list
data = []
data.append( (name, match) )
return render_template("created.html", data=data)
and use it in template
{% for row in data %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
</tr>
{% endfor %}

Could not parse the remainder: '((records_list.1.key.5)' from '((records_list.1.key.5)'

Obligatory "I am new to Django" here...
In my views I am creating a list, called records_list. Inside that list, I have another list in the position [0] and a dictionary in the position [1], as follows:
records_list = list()
list_one = Bet.objects.order_by('-game_date')
list_two = {}
Inside the "list_two", that is my dictionary, I have a key that is a date "April 2016", for ex, and a value that is a tuple:
list_two[aux_month_year] = (aux_wins, aux_losses, aux_voids, s_rate, i_rate, profit)
So I return this to my html:
records_list.append(list_one)
records_list.append(list_two)
return records_list
In the html, I want to create a table, and I start by checking if my profit is positive or not:
{% if records_list %}
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Wins</th>
<th>Losses</th>
<th>Void</th>
<th>Success Rate</th>
<th>Return on Investment</th>
<th>Profit</th>
</tr>
</thead>
{% for key in records_list.1 %}
{% if ((records_list.1.key.5) > 0) %}
<tr class="success">
<td>{{ key }}</td>
<td>{{ records_list.1.key.0 }}</td>
<td>{{ records_list.1.key.1 }}</td>
<td>{{ records_list.1.key.2 }}</td>
<td>{{ records_list.1.key.3 }}%</td>
<td>{{ records_list.1.key.4 }}%</td>
<td>{{ records_list.1.key.5 }}</td>
</tr>
However, I am getting the following syntax error here:
{% if ((records_list.1.key.5) > 0) %}
Error:
Could not parse the remainder: '((records_list.1.key.5)' from '((records_list.1.key.5)'
If someone could help me and point me to the right direction I would appreciate!
Thank you
The if tag does not support parentheses. From the docs:
Use of actual parentheses in the if tag is invalid syntax. If you need them to indicate precedence, you should use nested if tags.
In your case, the parentheses are not required, so just remove them:
{% if records_list.1.key.5 > 0 %}

Django For loop template for dict data

So in Python if i have a Dictionary rather than a list with a dataset, I would normally call (for example):
for i in myDictionary:
myDictionary[i]['event']
myDictionary[i]['timestamp']
etc.
But in Django this does not work:
{% for i in myDictionary %}
<tr>
<td> {{ myDictionary.i.event }}</td>
<td> {{ myDictionary.i.timestamp }}</td>
</tr>
Does not produce results - what's the optimal way to handle dictionaries with an arbitrary number of keys?
You have a weird structure. What you want is a list of dictionaries.
myDicts = []
for i in myDictionary:
data = {'event': '...', 'timestamp': '...'}
myDicts.append(data)
Then, you can loop over dictionary values by using the function .items, like in a normal loop (but don't include the parenthesis):
{% for elem in myDicts %}
{% for key, value in elem.items %}
<tr>
<td> {{ myDictionary.key }}</td>
<td> {{ myDictionary.value }}</td>
</tr>
{% endfor %}
{% endfor %}

Categories

Resources