Loop through an array django - slightly more complex - django

I am using a JQuery chart library where you pass values a format like [0,2,5,9].
I have an array in my views where I currently access each index to return the value rest 1 = arr[0], rest 2 = arr[1] ... and then passing these values from the view into my HTML page and inserting the values for the chart like [res1,res2]. This is not feasible because I never know the size of the array so it'd be a constant manual approach of accessing the array. Is there a way I easily loop through each one?
Slight problem. Currently after accessing each index I convert value to an int. So I don't think I'd be able to do it via looping through the html page - it'd have to be done via views. Unless I can somehow call conversion function defined in the view in the html page?
--- views ---
array
-> returns multiple string values i.e. name = paul, name = john
-> paul = arr[0]
-> function(paul['']) converts it to a string.
--- html page ---
{{paul}}
ideally i'd like to do:
[rather than refer to each index here just loop through all array values.. but somehow calling my conversion function too on each value else what I want to do won't work. ]
{% for values in array %}
[insert each one here and call the convert int function from views]

I might misunderstood your question, but sounds like you just want to pass a list of string to the template, loop on each item in the list and do some conversion. I'm not really sure which step did you get stuck but the simplest way is to do everything in the views.py:
views.py
def view_func(request):
array = [{'Speed': 2, 'Height': 1, 'PersonID': 1}, {'Speed': 2, 'Height': 1, 'PersonID': 1}]
# do the conversion on each value in the list
converted_array = [int(i['speed']]) for i in array]
context = {'array': array, 'converted_array': converted_array}
template:
<!-- to loop on original array -->
{% for value in array %}
{{ value }}
{% endfor %}
<!-- to loop on the converted array -->
{% for value in converted_array %}
{{ value }}
{% endfor %}

Related

Django Template For Loop Iterator Not Usable

In a Django template the following syntax works just fine:
{% for test in testing.1 %}
but when replacing the fixed 1 with a dynamic variable from an outer for loop it doesn't work at all:
{% for i in range %}
{% for test in testing.i %}
When printing {{ i }} it shows 1, 2 and 3 like it should. Do I have to convert the i-variable somehow? Or can't I use the iterator variable there?
As #svrw commented: a dictionary lookup can't use a variable as key. I had to prepare the data so that I could use
{% for element in range %}
{% for test in element %}
and get the correct output. My data in the views.py I changed from this:
range = {
1: data1,
2: data2,
3: data3
}
to:
data1 = [element1, element2, element3 ...]
...
range = [data1, data2, data3]

Django - Select from a list

I have a list :
logo_nofav = [('codwaw.png', 'codwaw'), ('lol.png', 'lol')]
In my template I can :
call the first in the list with {{logo_nofav.0}}
call the second with {{logo_nofav.1}}
just call the second element of the second in the list with {{logo_nofav.1.1}}
Now my question is, how could I just call the second element of each object.
We could image {{logo_nofav.x.1}} where "x" is a variable which means anywhere on the list.
I hop I was clear. Thanks
You could iterate through the list,
{% for item in logo_nofav %}
{{ item.1 }}
{% endfor %}

Output nested list to xlsx using Django

I have a complex nested list of models that looks like this:
hierarchy_tree = ['0000', 'hierarchy' [['0000-22', 'hierarchy2', [['0000-33', 'hiearchy3', [['0000-44-4444', 'hiearchy4', [['0000-55-5555-55', 'hiearchy5', []]]]]]]]]]
I am able to easily display this in a template using dot notation - example:
{% for hierarchy in hierarchy_tree %}
<tr class="item" data-id="{{system.0}}" data-parent="">
<td>
{{hierarchy.0}}
</td>
<td>
{{hierarchy.1.genericname}}
</td>
Now I am trying to output this to an .xlsx file but I cannot figure out how to pass all of the levels of this list? How can I do the same thing that I did in the template to pass this list to excel?
I have tried the following which will return the 1st list but throws an error (ValueError at /post/1/export/hierarchy/ - cannot covert(my passed in list)to excel) for the sublists because of the way that they are nested I believe.
for r in hierarchy_tree:
ws.append(r)
I have also tried and failed repeatedly to access the sublists using other methods.
So bottom line I need to figure out how to access and pass the values for the sublists - any ideas or help will be greatly appreciated?
Thank you
Comment: ... is just 1 row in the list ...
Python print a instance of Type list in one line, surounding with [ ... ].
Your hierarchy_tree is of Type list of n lists.
Every n't list in hierarchy_tree starts with [ and ends with ].
You have to break your hierarchy_tree into row Data.
For instance:
def treeWalk(tree, level=0):
rData = [ '' for i in range(level)]
for item in tree:
if isinstance(item, list):
if len(rData) > level:
ws.append(rData)
level += 1
treeWalk(item, level)
return
rData.append(item)
treeWalk(hierarchy_tree)
Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice: 4.3.3.2

How to identify gaps in a sequential list using Django templates

If I have an ordered sequential list in my django template:
my_list = [
(1, "Billy Holiday"),
(2, "Louis Armstrong"),
# Number 3 is missing!
(4, "Ella Fitzgerald"),
(5, "Frank Sinatra"),
]
And I want to show something like this in my html:
1. Billy Holiday
2. Louis Armstrong
-- Some rows may be missing --
4. Ella Fitzgerald
5. Frank Sinatra
Is there a clever way to do this? I'm trying to accomplish this using Django templates. The idea would be to look at the previous iteration of the loop, and identify if rows are missing based on the counter values.
It seems like you try to move some logic from views to templates. I would strongly advise against this approach. It is not testable, harder to maintain, most likely will conflict with DRY principle.
So just doing the work in the view would probably be better.
However, if you are totally adamant that you want this done in template, you can make your own template filter:
someapp/templatetags/app_tags.py
from django import template
register = template.Library()
#register.filter
def set_missing_items(collection):
new_list = []
last = 0
for item in collection:
if item[0] != last + 1:
new_list.append('-- Some rows may be missing --')
new_list.append(item)
last = item[0]
return new_list
And then use it as follows:
template.html
{% load app_tags %}
{% for item in list|set_missing_items %}
{{ item }}
{% endif %}
Make sure to follow all steps from the documentation to make your custom filters work (like having proper folder structure with __init__.py files, making sure that app that has those filters is installed, etc).
Maybe a simple approach will be build the list this way:
my_list = [
(1, "Billy Holiday"),
(2, "Louis Armstrong"),
(3, ""),
(4, "Ella Fitzgerald"),
(5, "Frank Sinatra"),
]
and write a if for take care of the blank data inside the loop.

String to Int --> Django

[{'age': 1}] being returned something alike to this after a query. This is in my view. Now in my HTML I want to refer to that value returned - in this case '1' if {{}} > 1 ... do something but it cannot do this because Could not parse the remainder: '{{age}}' from '{{age}}'. However if I define a random integer value in my view set it as i.e. 10 I can very easily refer to this variable in my html no problem. I'm presuming it's because it's printing'age' rather than just returning the result from the database. Any solutions to this ? I'm thinking about creating a definition which returns it into a string
You want {% if number > 2 %}. You use {{ number }} to include a variable in the template, but you don't use the double braces inside a template tag.