Get element of list by variable in Django template - python

I have line of code in Django template:
<h4>{{ totals.date.weekday }}</h4>
Totals is the Python list, how do i get item of this list by index stored in date.weekday?
This would look in Python like this:
totals[date.weekday]
Creating another variable, which stores date.weekday doesn't work
UPD:
I found a solution:
Just added element of totals list to template context in render
For example:
# ...
return render(request, 'template.html', context={'date_total'=totals[date.weekday()]})

You can access the array directly using
{{ totals.0.date.weekday}} where the 0 is the position that you want.
Also if you want to print all the elements in total you will need a for loop such as:
{% for d in totals %}
{{ d }}
{% endfor %}
about sorting, you can use the pipe order_by but I recommend you to pass the list already ordered from the views

You have to run the "for loop" for this.
{% with counts = 0 %}
{% while counts < totals.count %}
{% if counts == date.weekday %}
<h4>total.counts</h4>
{% endif %}
{% counts += 1 %}
{% endfor %}
I did not get your question completely but i think it might help.

Related

string in list of list

I have two lists like:
DevInDB = ['Dev1','Dev2','Dev3']
and
DevInMesh = [['Dev1',0,0],['Dev2',1,1]]
I want to know if, for any DevInDB string, there is the same string in DevInMesh.
I wrote this code that works (in python)
for dev in DevInDB:
if any(dev in DevMesh for DevMesh in DevInMesh ):
print(dev)
else:
print('no')
I try to ust this code in a HTML file using jinja, but the 'any' function doesn't work. How can I do it?
You need to compute this before sending it to jinja.
Ex:
DevInDB = ['Dev1','Dev2','Dev3']
DevInMesh = [['Dev1',0,0],['Dev2',1,1]]
DevInMesh = {k for k, *_ in DevInMesh}
DevInDB = [(i, i in DevInMesh) for i in DevInDB]
print(DevInDB)
I've done it this way:
{% for DevDB in DevInDB %}
{% set ns = namespace(foo=false) %}
{% for DevMesh in DevInMesh %}
{% if DevMesh [0] == DevDB %}
{% set ns.foo = True %}
{% endif %}
{% endfor %}
and later on:
{% if ns.foo %}
{% else %}
{% endif %}
You can replace the any expression with the simple list comprehension where non-empty list will be True:
[1 for DevMesh in DevInMesh if dev in DevMesh]
Or better is to remove the computational part from template because a template is the view part that works on presentation level of the context, such that all pre-computed expressions should be stored in the context and only printed in the template.

django dictionary of querysets

i made i dictionary of querysets in one of my views :
list =[]
while(x<100 and i>0):
order_qs_1 = Order.objects.filter(timestamp__range=[start_date, end_date])
x = x+1
i=i-j
list.append(order_qs_1)
context= {
'list':list,
}
but now i don't know how to access the data inside the dictionary in my template
in my template i did something like this :
{% for item in list %}
{{ item }} </br>
{% endfor %}
this is what it renders:
the random numbers and characters are the order_id in my order model
the queryet is a list of orders coming from my order model
but this not what i want , i want the access the data inside each queryset
You can iterate over the querysets. For example:
{% for qs in list %}
<p>
{% for order in qs %}
{{ order }}
{% endfor %}
</p>
{% endfor %}
Here we thus iterate over the querysets qs, and for example render the order. You can thus render individual data of that order, for example {{ order.pk }} for the primary key.

How can i access a jinja2 variable outside the for loop?

im trying to use a for loop to add up some numbers for each day
and i would like to access the variable outside the for loop im not sure how to go about this I am using the flask framework with python and just come from weppy where this was not a problem is there a way to make it work the same way in flask?
here is some simple code
{% set newtotal = 0 %}
{% for item in daily: %}
{% set newtotal = newtotal + item[10]|float %}
{% endfor %}
<div class="bottom">
<span>Total: {{ newtotal }}</span>
</div>
the numbers collected by item[10] are dollar values
if i place the {{ newtotal }} before the endfor it shows every value as its being added up this is not what I want
EDIT:
if it helps daily is a list of 8 tuples
Please keep in mind that it is not possible to set variables inside a block or loop and have them show up outside of it.
As of version 2.10 this can be handled using namespace objects which allow propagating of changes across scopes.
Here is your code using namespace:
{% set ns = namespace (newtotal = 0) %}
{% for item in daily: %}
{% set ns.newtotal = ns.newtotal + item[10]|float %}
{% endfor %}
<div class="bottom">
<span>Total: {{ ns.newtotal }}</span>
</div>
One solution (probably the "simplest") would be to change your Python script to pass in a variable named newtotal that would simply be the length of the daily list!
Alternatively, you could use the length filter:
{{things|length}}
In which case your code could look something like this:
{% set newtotal = 0 %}
{% for item in daily: %}
{% set newtotal = newtotal + item[10]|float %}
{% endfor %}
<div class="bottom">
<span>Total: {{daily|length}}</span>
</div>
Hope it helps!
Additional Sources:
jinja2: get lengths of list
How do I access Jinja2 for loop variables outside the loop?
EDIT
Sorry, I misread the question!
You can use the sum filter instead ({{ list | sum() }}).
So your code could look like:
{% set newtotal = 0 %}
{% for item in daily: %}
{% set newtotal = newtotal + item[10]|float %}
{% endfor %}
<div class="bottom">
<span>Total: {{ daily | sum() }}</span>
</div>
New sources:
Documentation
Sum elements of the list in Jinja 2
Use the namespace object.
https://jinja.palletsprojects.com/en/master/templates/#assignments
Here’s a working example from my config.
{% set i= namespace(fxp0_ip=0) %}
{% set i= namespace(mgmt_ip = 0) %}
{% set i= namespace(loopback_ip = 0) %}
{% set i= namespace(lan_ip = 0) %}
{% set i= namespace(wan_ip = 0) %}
{% for interface in device_vars.interfaces %}
{% elif interface.name == "ge-0/0/0" %}
{% set i.mgmt_ip = interface.ip_addr %}
{% elif interface.name == "lo0" %}
{% set i.loopback_ip = interface.ip_addr %}
{% elif interface.name == "ge-0/0/2" %}
{% set i.lan_ip = interface.ip_addr %}
{% elif interface.name == "ge-0/0/1" %}
{% set i.wan_ip = interface.ip_addr %}
{% endif %}
{% endfor %}
{{i.mgmt_ip}}
{{i.wan_ip}}

How to get Substr of values

Hi I have the following query in my views.py
m = Request.objects.filter(Q(type__icontains='4'), Q(wt__in =['giga','mega']))
context['all_items'] = m.values('type1').order_by('type1')
Its giving values sasoo, masoo, pisoo, kusoo etc.
How can I implement the Django Substr in this case so that my html will display values as sa, ma, pi, ku, ..
You can annotate the model
from django.db.models.functions import Substr
m = Request.objects.filter(Q(type__icontains='4'), Q(wt__in =['giga','mega']))
context['all_items'] = m.annotate(mysubstring=Substr('type1',1,2)).order_by('type1')
In template:
{% for obj in all_items %}
{# Use obj.mysubstring #}
{% endfor %}
You can use slice filter in your template:
{% for item in all_items %}
{{ item.type1|slice:":2" }}
{% endfor %}
One liner
context['all_items'] = [i[:2] for i in context['all_items']]

Django - How to do tuple unpacking in a template 'for' loop

In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this:
[ Product_Type_1, [ product_1, product_2 ],
Product_Type_2, [ product_3, product_4 ]]
In plain old Python, I could iteration the list like this:
for product_type, products in list:
print product_type
for product in products:
print product
I can't seem to do the same thing in my Django template:
{% for product_type, products in product_list %}
print product_type
{% for product in products %}
print product
{% endfor %}
{% endfor %}
I get this error from Django:
Caught an exception while rendering: zip argument #2 must support iteration
Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product_type, a simple one-to-many relationship).
Obviously, I am quite new to Django, so any input would be appreciated.
Another way is as follows.
If one has a list of tuples say:
mylst = [(a, b, c), (x, y, z), (l, m, n)]
then one can unpack this list in the template file in the following manner.
In my case I had a list of tuples which contained the URL, title, and summary of a document.
{% for item in mylst %}
{{ item.0 }} {{ item.1}} {{ item.2 }}
{% endfor %}
it would be best if you construct your data like {note the '(' and ')' can be exchanged for '[' and ']' repectively, one being for tuples, one for lists}
[ (Product_Type_1, ( product_1, product_2 )),
(Product_Type_2, ( product_3, product_4 )) ]
and have the template do this:
{% for product_type, products in product_type_list %}
{{ product_type }}
{% for product in products %}
{{ product }}
{% endfor %}
{% endfor %}
the way tuples/lists are unpacked in for loops is based on the item returned by the list iterator.
each iteration only one item was returned. the first time around the loop, Product_Type_1, the second your list of products...
You must used this way:
{% for product_type, products in product_list.items %}
{{ product_type }}
{% for product in products %}
{{ product }}
{% endfor %}
{% endfor %}
Don't forget the variable items in the dictionary data
If you have a fixed number in your tuples, you could just use indexing. I needed to mix a dictionary and the values were tuples, so I did this:
In the view:
my_dict = {'parrot': ('dead', 'stone'), 'lumberjack': ('sleep_all_night', 'work_all_day')}
In the template:
<select>
{% for key, tuple in my_dict.items %}
<option value="{{ key }}" important-attr="{{ tuple.0 }}">{{ tuple.1 }}</option>
{% endfor %}
</select>
Just send the template a list of product types and do something like:
{% for product_type in product_type_list %}
{{ product_type }}
{% for product in product_type.products.all %}
{{ product }}
{% endfor %}
{% endfor %}
It's been a little while so I can't remember exactly what the syntax is, let me know if that works. Check the documentation.

Categories