I'm using the forloop counter to assign unique ids to three which I later populate with data.
<tbody>
{% for d in data %}
<tr>
<td id="menge{{ forloop.counter }}">{{ d.menge }}</td>
<td id="preis{{ forloop.counter }}" name="preis">{{ d.preis }}</td>
<td>{{ d.einheit }}</td>
<td id="preisprostuekc{{ forloop.counter }}" name="{{ d.id}}">
</td>
</tr>
{% endfor %}
</tbody>
Lets say the loop runs 10 times. This means the last assigned value is 10. Can i get that value, the last value of the counter, to reuse it in a javascript function? If yes: how? Thanks!
Normally if data is an iterable where one can call len(…) on, you can use this to determine the number of objects, so you can use the |length template filter:
<script language="JavaScript">
var value = {{ data|length }};
</script>
You can use forloop.last
Like this:
{% for d in data %}
{% if forloop.last %}
<div>Last number = {{ forloop.counter }} </div>
{% endif %}
{% endfor %}
Related
I have the this output in the browser from HTML template:
{'coin__name': 'Bitcoin', 'total': Decimal('1498824')}
{'coin__name': 'Ripple', 'total': Decimal('335227')}
How can I show in an html template separately the key and the value(without saying Decimal)?
Desired outcome:
Bitcoin, 1498824
Ripple , 335227
I provide the query and the html template below:
views.py:
test = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price' ) * Sum('number_of_coins'))).order_by('-total')
template.html
<table class="table table-striped">
<tr>
<th>Current dict pair</th>
<th>Just the name of the crypto</th>
<th>Just the price of the crypto</th>
</tr>
{% for item in test %}
<tr>
<td>{{ item }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
</tr>
{% endfor %}
Update template with below code:
{{ test }} <!-- test is list of dictonaries -->
<br>
{% for item in test %} <!-- Loop to get each item(sub dictonary) from list-->
<br>
{% for key,value in item.items %} <!-- Getting key values pairs from each sub dictonary item -->
{% if forloop.last %} <!-- Checking if last iteration of loop just to add "::" after each value -->
{{ value }} <!-- only displying values not keys from each sub dictionary -->
{%else%}
{{value }} ,
{% endif %}
{% endfor %}
{% endfor %}
Refer to this answer for removing decimal from result.
Django: remove Decimal prefix from queryset annotated field, when requesting values
Try fetching both the key and the value from the dictionary in the loop:
{% for key, value in test.items %}
<tr>
<td>{{ key }}</td>
<td>{{ value }}</td>
</tr>
{% endfor %}
If you want to format Decimal value see docs
I have context as below :
context = {
'author': author,
'books':books,
}
Now I need to use author and books in One for loop like this :
{% for each in ***author & books*** %}
<tr>
<td>{{ each.author.name }}</td>
<td>{{ each.book.name }}</td>
<td>{{ each.book.pubishDate }}</td>
</tr>
{% endfor %}
How to make such a for loop in Django template?
Thanks all.
join 2 dictionaries into a list before sending it to the template(i.e in the view):
dicts = [dict1, dict2]
and try this:
{% for d in dicts %}
<tr>
<td> {{ d.x }} </td>
<td> {{ d.y }} </td>
</tr>
{% endfor %}
I created a table with 3 columns.
Column one is the main test name.
Column two is the sub-test name.
Column three is the pass/fail status.
I would like to remove duplicates in column so that sub-test and status can look like they are grouped with the main test.
I tried to use the unique filter in the html below <td>{{ value['status'][0][0]|unique }}</td> but no luck there.
Basically trying to remove duplicates from column 1 of my table.
<table style="width: 100%" class="flex-container">
<tbody>
{% for key, value in testCaseStatusDict.items() %}
<tr>
<td>{{ value['status'][0][0] }}</td>
<td style="text-align: left; vertical-align: middle"><b>{{ value['testCaseName']}}</b></td>
{% for status in value['status']%}
{% if status[2] == 'FAIL' %}
<td style="background-color: red; text-align: center"><br>{{ status[2] }} <br> {{ status[3] }}</td>
{% else %}
<td style="background-color: green; text-align: center"><br>{{ status[2] }} <br> {{ status[3] }}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
Desired look:
Actual output:
You can try this: Check if you are already in your actual test case if yes don't print the status again else print it.
{% set status_before = [] %}
{% for key, value in testCaseStatusDict.items() %}
<tr>
{% if value['status'][0][0] in status_before %}
<td></td>
{% else %}
<td>{{ value['status'][0][0] }}</td>
{% set __ = status_before.append(value['status'][0][0]) %}
{% endif %}
...
#Edit Try it with mutable list, even if it's ugly. Looks like updating a variable inside a loop is not supported: https://github.com/pallets/jinja/issues/641
This question already has answers here:
Using index from iterated list
(2 answers)
Closed 7 years ago.
I'm passing 4 lists of the same length and the length of the lists to my template. How do I iterate over the lists?
views.py
def allbooks(request):
ID = [1,2]
bookName = ["Python", "Java"]
author = ["idk", "who"]
copies = [3,7]
return render(request, 'allbooks.html',{'ID':ID,'bookName':bookName, 'author':author, 'copies':copies,'range':range(len(ID))})
allbooks.html
{% extends 'base.html' %}
{% block content %}
{% if user.is_authenticated %}
<div>
<h3>
List of books:
</h3>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Book Name</th>
<th>Author</th>
<th>Number of copies</th>
</tr>
</thead>
<tbody>
{% for x in range %}
<tr>
<td>{{id[x]}}</td>
<td>{{bookName[x]}}</td>
<td>{{author[x]}}</td>
<td>{{copies[x]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<h3>You must login to continue.</h3>
{% endif %}
{% endblock %}
I've tried replacing the variable x with {% forloop.counter0 %} but to no avail. How can I fix this?
Zip all your lists to one list of tuples:
books= zip(ID, bookName, author, copies)
return render(request, 'allbooks.html',{ "books": books} )
Than loop over it in templates like:
{% for book in books %}
<tr>
<td>{{ book.0 }}</td>
<td>{{ book.1 }}</td>
<td>{{ book.2 }} </td>
<td>{{ book.3 }}</td>
</tr>
{% endfor %}
I suggest a better structure for your book info:
books = [
{ "id":1, "name": "Python", "author":"idk", "copies": 1},
{ "id":2, "name": "Java", "author":"idk2", "copies": 3}
]
than iterate through it:
{% for book in books %}
<tr>
<td>{{ book.id }}</td>
<td>{{ book.name }}</td>
<td>{{ book.author }} </td>
<td>{{ book.copies }}</td>
</tr>
{% endfor %}
python 2.6, with Django 1.3.1 on Redhat 6.3
In Django how would I go about changing the background colour of a table cell depending on it's value, as in if it is over 10 it's red, between 7 and 9 it's orange, below 7 is green etc..
The data is coming from a non django database/model.
I am using a standard template to iterate over the table, but would have no problem using a custom template for this.
I see the following
Link
that deals with changing cell colour but it seems to be based on a concrete value in the cell as opposed to being within a range.
using the following test code for a view
def dashboard(request):
if request.user.is_authenticated():
user = request.user.first_name
else:
return redirect('/bcpm/login')
table_headers = ['Colmun1','Column2','Column3']
table_data = [['test1',2,3],['test2',2,4],['test3',5,5]]
page_title = 'Dashboard'
template_dict = {'header_list':table_headers, 'page_title':page_title,
'results':table_data,'username':user}
return render_to_response('dashboard.html',template_dict)enter code here
and the following generic table template:
<table border=1 width=98% style="margin-left:12px;">
<tr>
{% for item in header_list %}
<th>{{ item }}</th>
{% endfor %}
</tr>
{% for row in results %}
<tr>
{% for line in row %}
<td>{{line}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Thanks.
Almost solved;
With the help of brianbuck below i came up with the following,
in the view:
def dashboard(request):
if request.user.is_authenticated():
user = request.user.first_name
else:
return redirect('/login'
table_headers = ['Column1','Column2','Column3']
table_data = [['name','thing',8],['name','thing',5]]
page_title = 'Dashboard'
template_dict = {'header_list':table_headers, 'page_title':page_title,
'results':table_data,'username':user}
return render_to_response('dashboard.html',template_dict)
in the template;
<table border=1 width=68% style="margin-left:12px;">
<tr>
{% for item in header_list %}
<th>{{ item }}</th>
{% endfor %}
</tr>
{% for element in results %}
<tr>
<td> {{ element.0 }} </td>
<td> {{ element.1 }} </td>
{% if element.3 > 7 %} <td class="red"> {{ element.3 }} </td>
{% else %} <td class="green"> {{ element.3 }} </td> {% endif %}
</tr>
{% endfor %}
</table>
{% endif %}
I really could not get it to do an {% if or %}
When I tried to set it up to do a
"greater than or equal to 7 or less than or equal to 8"
it would always evaluate to this expression for a number higher than 7, even though the first if statement should be true for anything higher than 9.
I am using Django 1.3 and I think there may be some limitations of the if/else and the multiple evaluations, either way I have it 80% working with two values red/green and that is good enough for the moment.
Thank you all.
Got it to work like this;
{% for element in results %}
<tr>
<td> {{ element.0 }} </td>
<td> {{ element.1 }} </td>
<td> {{ element.2 }} </td>
<td> {{ element.3 }} </td>
{% if element.4 > 8 %} <td class="red"> {{ element.4 }} </td>
{% else %}{% if element.4 > 8 or element.4 >= 5 %} <td class="orange"> {{ element.4 }} </td>
{%else %}{% if element.4 < 5 %}<td class="green"> {{ element.4 }} </td>
{% endif %}{% endif %}{% endif %}
<td> {{ element.5 }} </td>
This would not be required if you have a version of Django that supports elif or if you add some of the django snippets that are available to extend your django installation.
Hurrah.
This assumes you have three classes named:
td.red {
backgroundColor: red;
}
td.orange {
backgroundColor: orange;
}
td.green {
backgroundColor: green;
}
...
Django 1.3 doesn't have elif so you will probably have to do it a bit more clunky.
<td class="
{% if val >= 10 %}red{% endif %}
{% if val >= 7 or val <= 9 %}orange{% endif %}
{% if val < 7 %}green{% endif %}">
{{ val }}
</td>
I wanted to do this only in admin.py.
Let's say your column is called col :
You want to set the column to green if its value is bigger than 0 and to red if the opposite is true.
def TableAdmin(admin.ModelAdmin)
def col_(self, obj):
green_style = "<script>document.querySelectorAll('.green_table_elem').forEach(elem => { elem.parentElement.style.background = 'green'; })</script>"
red_style = "<script>document.querySelectorAll('.red_table_elem').forEach(elem => { elem.parentElement.style.background = 'red'; })</script>"
if obj.col > 0:
return mark_safe(f'<div class="green_table_elem">{obj.col}</div> {green_style}')
else:
return mark_safe(f'<div class="red_table_elem">{obj.col}</div> {red_style}')
list_display = ('col_',)
This colors the td (column) itself and not the added div like some answers do.