How to store and access values outside loop in jinja - flask

I have seen few Questions asking same , but I could not figure out how to
I have a for loop as:
{% for brands in data %}
{{ brands['brand'] }} // 'test1','test2'.....
{% endfor %}
I am trying to access the brands['brand'] values outside of loop , I am doing as:
{% set newlist = [] %}
{% for brands in data %}
{% set newlist = newlist.append(brands['brand']) %}
{{ brands['brand'] }} // 'test1','test2'.....
{% endfor %}
now when I access newlist as {{ newlist }} after loop it gives me result
But, May I know how can i access the newlist above declaration ? (sorry if this doesn't make any sense)
Any help is appreciated ...TIA

Please change this piece of code :
{% set newlist = newlist.append(brands['brand']) %}
to this :
{% set newlist = newlist.append( {{ brands['brand'] }} ) %}

Related

Accessing multiple dictionaries in list using for loop in Django Templates

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.

how to use objects in django template

I have such object:
data[ 'aaa' ] = ['1', 'something1']
data[ 'bbb' ] = ['2', 'something2']
And want to display it (using loop ) in template :
{% for row in data %}
<span>{{ row }}</span>>
{% for d in data.row %}
{{ d.0 }} || {{ d.1 }}
{% endfor %}
{% endfor %}
But i see only values within the span tag ( even though array is not empty )
Can you tell me what I am doing wrong ?
Thanks in advance,
The way you're trying to iterate over each row doesn't make sense - either you iterate, or you fetch by index, but doing both will not work. Try this instead:
{% for row in data %}
{{ d.0 }} || {{ d.1 }}
{% endfor %}

Django template nested for loop with if statement not working

I need to have a nested loop in my Django template, where the outer loop goes through a list of objects, and the inner loop goes through a list of those object id's, and I want to only do something for the id's on the inner list, it never executes however. I think it has something to do with the condition for the if statement, because if I replace it with a true statement it works but it doesn't work as it is now
(I have checked to see that the id's overlap)
{% for outer in outer_obj_list %}
{% for inner_id in inner_id_list %}
{% if outer.id == inner_id %}
// do something
console.log({{inner_id}});
console.log({{outer.id}});
{% endif %}
{% endfor %}
{% endfor %}
Syntax seems correct. I would just verbosely output everything.
Perhaps it should be something like this:
{% for main_obj in main_obj_list %}
main_obj: {{ main_obj }}
{% for obj_id in obj_id_list %}
obj_id: {{ obj_id}}
main_obj: {{ main_obj.id}}
{% if main_obj.id == obj_id %}
// do something
match: {{main_obj.id}} == {{obj_id}} ;
{% endif %}
{% endfor %}
{% endfor %}
Brother I am also face this problem so my clever mind get some clever solution about this problem we can do that with JavaScript easily so we need to run it in JavaScript and then.
{% for outer in outer_obj_list %}
{% for inner_id in inner_id_list %}
if(outer.id == inner_id.id ){
console.log({{inner_id.id}});
console.log({{outer.id}});
//And also if we reserve place in DOM then we can
//change the inner Html of them easily like.
//demo = document.getElementById("demo");
//demo.innerHTML = inner_Id.id or outer.id
}
{% endfor %}
{% endfor %}

Template adding value in variable declared using with

Can some one please explain me why the below code is not adding the value in current_count variable. Also I am using django version 1.3. The below code gives following output.
0
"image"
10
"image"
10
"image"
.
.
.
The "image" means actual image is shown.
What I want is "only show 4 images".
{% with current_count=0 %}
{% for row in people|slice:":4" %}
{% if row %}
{% for event in row %}
{% if current_count < 4 %}
{{current_count}}
<div class="latest-photos-image-box">
<img src="{{ event.mainthumb.url }}" alt="{{ event.title }}" />
</div>
{% endif %}
{{ current_count|add:"1" }}
{% endfor %}
{% endif %}
{% endfor %}
{% endwith %}
The problem here is that {{ current_count|add:"1" }} does the addition but doesn't store anything. Please use the loop counters forloop.counter instead.
However, if you need a counter that works regardless of nesting level; here is a recipe (haven't tested but should work):
>>> def monotonic():
... count = 0
... while True:
... yield count
... count += 1
...
>>> counter = monotonic()
>>> # pass it to you request context dictionary
and use {{ counter.next }} each time you need it.
Please also check out this question: Flatten list of lists , you may want to flatten your list of rows of people to a more simple list of people that you can then slice.
{% for event in row|slice:":4" %}
And get rid of the rest.

Django DRY List iteration

As someone who is just starting to use Django in my scarce time, I appreciate in advance your time in helping me learn how to make my code cleaner and correct.
I have two lists comprised of two querysets as follows:
company_list = [Company_stats.objects.filter(period__exact=P, company_name__in=master_names)]
industry_list = [Industry_stats.objects.filter(period__exact=P, industry_name__in=master_names)]
I iterate through both lists in my template to create a small table.
{%for c in company_list%}
{%for z in c %}
{{ z.company_name }}
{{ z.nxt_m_ret_est }}
{{ z.nxt_m_ret_rat }}
{% endfor %}
{% endfor %}
{%for c in industry_list%}
{%for z in c %}
{{ z.industry_name }}
{{ z.nxt_m_ret_est }}
{{ z.nxt_m_ret_rat }}
{% endfor %}
{% endfor %}
This works fine, however, since I am using the same code except for z.industry_name vs. z.company_name I was wondering whether you could help me figure out a better way to do this.
I have tried combining the lists into one list with both querysets in it and that works except for the obvious issue that I don't know how to tell it to retrieve z.company_name or z.industry_name depending on the queryset where the data is coming from, because everything became part of the same list.
Once you've changed the field to name on both models you can put both querysets into the same list and then iterate over that.
master_list = [model.objects.filter(period__exact=P, name__in=master_names) for model in (Company_stats, Industry_stats)]
...
{% for l in master_list %}
{% for i in l %}
{{ i.name }}
{{ i.nxt_m_ret_est }}
{{ i.nxt_m_ret_rat }}
{% endfor %}
{% endfor %}
If you want to have the code be more generic, it would help to make your names more generic. Would it be possible for you to change industry_name and company_name to just name throughout your system?