When i receive a associative array namely dictionaries in django template which as follows
"receivable_aging": {
"age5": 235114.91999999998,
"age4": 235114.91999999998,
"age3": 0,
"age2": 0,
"age1": 0 }
I tried to print like this
{% for key, value in receivable_aging.items %}
{{ value }}
{% endfor %}
I want to print age1 to age4 in ascending order. How can I achieve this without if or minimal steps.
Sort items in your views.py:
return render_to_response('page.html',
{'receivable_aging': sorted(receivable_aging.items())})
Then print them in template:
{% for key, value in receivable_aging %}
{{ value }}
{% endfor %}
Hope it helped.
Related
I have been working on a project and it requires me to access dictionaries that are in a list. I am using Django 2.0. This is my code here.
{% if dictdata %}
{% for x in range %}
{{ "in loop" }}
{{ dictdata.x.name }}
{% endfor %}
{{ dictdata.0.name }}
{{ dictdata.1.name }}
{% endif %}
The two statement after the for loop are working fine. But the one in the loop is not returning anything but printing the message 'in loop'. dictdatais a list containing dictionaries.
It is not clear what the value of your range varable is. So assuming dictdata is close to the following:
dictdata = [
{'name': 'Bob'},
{'name': 'John'}
]
You can loop over them in your template as follows:
{% for d in dictdata %}
{{ d.name }}
{% endfor %}
Documentation about looping in a template can be found here.
I'm using django's template system, and I'm having the following problem:
I pass a dictionary object, example_dictionary, to the template:
example_dictionary = {key1 : [value11,value12]}
and I want to do the following:
{% for key in example_dictionary %}
// stuff here (1)
{% for value in example_dictionary.key %}
// more stuff here (2)
{% endfor %}
{% endfor %}
However, this does not enter on the second for loop.
Indeed, if I put
{{ key }}
on the (1), it shows the correct key, however,
{{ example_dictionary.key }}
shows nothing.
In this answer, someone proposed using
{% for key, value in example_dictionary.items %}
However, this does not work in this case because I want (1) to have information regarding the particular key.
How do I achieve this? Am I missing something?
I supose that you are looking for a nested loop. In external loop you do something with dictionary key and, in nested loop, you iterate over iterable dictionary value, a list in your case.
In this case, this is the control flow that you need:
{% for key, value_list in example_dictionary.items %}
# stuff here (1)
{% for value in value_list %}
# more stuff here (2)
{% endfor %}
{% endfor %}
A sample:
#view to template ctx:
example_dictionary = {'a' : [1,2]}
#template:
{% for key, value_list in example_dictionary.items %}
The key is {{key}}
{% for value in value_list %}
The key is {{key}} and the value is {{value}}
{% endfor %}
{% endfor %}
Results will be:
The key is a
The key is a and the value is 1
The key is a and the value is 2
If this is not that you are looking for, please, use a sample to ilustrate your needs.
I'm coming from this question Use variable as dictionary key in Django template
i've this context created in my view:
{'cats': {'LIST1': ['a','b','c'], 'LIST2': ['aa','bb','cc','dd'], 'LIST3': ['f','g']}}
what i want to do is to print the list title and then all the items, something like
LIST1:
- a
- b
- c
for all the lists, so i did this in my template
{% for l_name, l in cats %}
{{ l_name }}
{%for lv in l %}
{{ lv }}
{% endfor %}
{% endfor %}
and this prints only the list names, without printing out the list. where's the mistake?
thanks
If you want to iterate over keys and values, you can use:
{% for name, lst in cats.iteritems %}
....
{% endfor %}
This just calls the iteritems method of a dictionary, which returns an iterator over a list of 2-tuples.
Django's {% for %} tag documentation has some nice example of this too.
Just for the record, the problem is how the data are created. so instead of
{'cats': {'LIST1': ['a','b','c'], 'LIST2': ['aa','bb','cc','dd'], 'LIST3': ['f','g']}}
i need a list of touple so:
{'cats': [('LIST1', ['a','b','c']), ('LIST2', ['aa','bb','cc','dd']), ('LIST3', ['f','g'])]}
I am populating a list in my view:
hits_object = {}
hits_object['Studio'] = hitlist('Studio',days)
hits_object['Film'] = hitlist('Film',days)
hits_object['Actor'] = hitlist('Actor',days)
hits_object['Historical Event'] = hitlist('Event',days)
hits_object['Pop Culture'] = hitlist('Pop_Culture',days)
Then I am displaying it in my template:
{% for model, hits in hits_object.items %}
{% if hits %}
<u> Most {{ model }} views in last {{ days }} days</u>
<ol>
{% for hit in hits %}
<li>{{ hit.name }} - {{ hit.count }}</li>
{% endfor %}
</ol>
</u>
{% endif %}
{% endfor %}
The problem is that the models display in a seemingly random order: first Actor, then Studio, Historical Event, Film, etc.
How can I force the for loop in the template to iterate the object in a specific order?
Dictionaries are unordered. If you need to preserve insertion order, use an ordered dict implementation - there's one in django.utils.datastructures.SortedDict, for example.
Or, since you don't seem to be using the key of the dictionary but are just iterating through, appending to a simple list would seem to be easier.
As Daniel explained, dictionaries are accessed randomly. Here is one way to do what you want:
hits_object = list()
hits_objects.append(
(hitlist('Studio',days),
hitlist('Film',days),
hitlist('Actor',days),
hitlist('Event',days),
hitlist('Pop_Culture',days))
In your view:
{% for studio,film,actor,event,pop_culture in hits_objects %}
# do something...
{% endfor %}
I have some loop on the page and need list item depending from loop number.
When I call:
{{ mylist.1 }}
{{ mylist.2 }}
{{ mylist.3 }}
all works fine but what I really need is something like:
{% for x in somenumber|MyCustomRangeTag %}
{{ mylist.x }}
{% endfor %}
MyCustomRangeTag gives me Python range() it works and I already have x as number. So x is 1, 2, 3 etc. depending from loop number.
Is this possible and how?
This is not possible directly because Django thinks that "x" is the key to lookup in mylist - instead of the value of x. So, when x = 5, Django tries to look up mylist["x"] instead of mylist[5].
Use the following filter as workaround:
#register.filter
def lookup(d, key):
return d[key]
and use it like
{{ mylist|lookup:x }}
The slice tag in Django templates may use python's slicing code, but the syntax is unmistakably different. For instance, if you wanted to get an element of a sequence with a variable, in python you'd write something similar to the following:
>>>mylist = ["0th Element", "1th Element"]
>>>zero, one = 0, 1
>>>mylist[zero]
"0th Element"
>>>mylist[one]
"1th Element"
Using this syntax with the Django slice template tag will return a sliced list in every case, of dubious utility for getting an item of known index:
{% with "0" as zero %}
{% with "1" as one %}
{% with "2" as two %}
{{mylist|slice:zero}} {{mylist|slice:one}} {{mylist|slice:two}}
{% endwith %}
{% endwith %}
{% endwith %}
Renders to the html:
[] ["0th Element"] ["0th Element", "1th Element"]
Note the differences: you are getting the result of mylist[:x] instead of mylist[x].
Django provides enough tools to work around this. The first trick is to use explicit slices like 0:1 for your indices, and then |join:"" the resultant list into a single element. Like so:
{% with "0:1" as zero %}
{{mylist|slice:zero|join:""}}
{% endwith %}
Yields:
0th Element
This comes in particularly handy if you need to access a parent loop's index when dealing with an iterable inside a child loop:
{% for parent in parent_loop %}
{% cycle "0:1" "1:2" "2:3" as parent_loop_index silent %}
{% for child in child_loop %}
{{child|slice:parent_loop_index|join:""}}
{% endfor %}
{% endfor %}
Completed with nothing but stock parts, although I don't think Django has implemented achievements yet.
I notice that #e-satis mentioned it, but I think the built-in slice template tag deserves some love.
{{ item | slice:"2" }} #gets the third element of the list
Are you sure you can't just do:
{% for item in mylist %}
{{ item }}
{% endfor %}
With the slice filter, you can even do some customisation.
Following worked for me
{% for 1,2,3 in mylist %}
# do stuff
Just don't use brackets around 1,2,3