How to loop through dictionary in jinja template - python

I have a dictionary that looks something like this:
{
'Team Starwars': {'Luke Skywalker': {('Jedi', 100)}}
'Team helloworld': {'Beginner': {('newbie', 100)}}
}
And now I want to iterate through the dictionary with jinja in a template.
I have tried somethings but can't iterate through it correctly.
The code I have now looks something like this:
{% for team_name in team_resource %}
{% for team, name in team_resource.items %}
{% for role, allocation in subrole %}
{% if forloop.counter0 != 0 %}<br>{% endif %}
{{role}} {{allocation}} %
{% endfor %}
{% endfor %}
team_resource is the dictionary that I pass to the template, and in the first loop I can access the first part of the dictionary and print out like Team Starwars and Team helloworld', but can't access the rest of the dict.
How should I do this?

You should use team_resource.items() instead of team_resource.items to access dict items.

What you refer to as 'the rest of the dict' is actually the value of the key you managed to retrieve successfully.
Without testing, I believe the variable name is the one that holds the {'Luke Skywalker': {('Jedi', 100)} part of the dictionary in your example.

Related

Iterating through a python dictionary in flask jinja

I have a dictionary which has all the country codes and the corresponding country names, a sample of it looks like this:
{'AF': 'Afghanistan'}
{'AL': 'Albania'}
{'DZ': 'Algeria'}
{'AD': 'Andorra'}
{'AO': 'Angola'}
When i followed this stack overflow question: How to iterate through a list of dictionaries in Jinja template? to try and iterate through the countries I had an issue as it's not adding any elements.
This is my code:
{% extends "base.html" %} {% block title %}Test{% endblock %}
{% block content %}
<div class="container pt-5">
<h1 align="center">TEST PAGE</h1>
</div>
{% for dict_item in countries %}
{% for key,value in dict_item.items %}
<h1>Key: {{ key }}</h1>
<h2>Value: {{ value }}</h2>
{% endfor %}
{% endfor %}
{% endblock %}
It's not adding any headings and when i tried dict_items.items() (with brackets after items), I got an error of: jinja2.exceptions.UndefinedError: 'str object' has no attribute 'items'
I'm not too sure what's going wrong. Any help would be much appreciated.
(Just incase it's useful, this is my views.py:)
#views.route("/test", methods=["GET"])
#login_required
def test():
countries = Country.query.all()
for country in countries:
countriess = {}
countriess[country.country_code] = country.country_name
print(countriess)
return render_template("TEST.html", user=current_user, countries=countriess)
Try changing views.py to:
#views.route("/test", methods=["GET"])
#login_required
def test():
countries = Country.query.all()
countriess = []
for country in countries:
countriess.append({country.country_code: country.country_name})
return render_template("TEST.html", user=current_user, countries=countriess)
This code will create a list of dictionaries countries, there is not need to change the templating code.
in views.py, you set countries=countriess for template rendering. countriess is re-initialised in the for loop in the test function (countriess = {}), so the countriess passed along to the template is actually a {country_code: country_name} pair for the last country from the countries list.
Going back to the actual error though: when you iterate over countries dictionary within the template ({% for dict_item in countries %}), you actually iterate over keys of countries, which, as I said before, is countriess from the views.py, so basically you just retrieve the country_code of the last country from countries. So the dict_item is actually a string (country code), hence you get the error for {% for key,value in dict_item.items %}, thinking that it is actually a dictionary and not a string.
TL;DR I think that you meant to do countries=countries rather than countries=countriess in views.py. Then the rest of the code would make sense. (I assume the for loop with countriess was just for debugging?)

Dealing with json type data in a template

I am after some advice. I know what I need to do, but not sure how I can do it
I send data to a template that comes from from a database
Let's say the database has two fields
Field one (name)
Name of a person
Field two some json (the json has a structure like this, with many field:value)
{
"field1":"value1",
"field2":"value2"
}
I can output this as
Field one (name) Field two (json)
What I actually want to do though, is loop through the json, and print out the values, so like this
Name of a person field1|field2
I am a bit lost on how I can do that
I tried something like this
{% for anitem in fieldtwo %}
<div>{{ anitem }}</div>
{% endfor %}
But that just seems to print out each character
Is what I need to do achievable? I am thinking I just have the whole approach wrong
Thanks
Grant
In the end, I ended up using another dictionary and then pass that through to the template
I loop through the queryset in the view to populate the dictionary
In the template I then did this (alloweddomains is from the view)
{% for testcaseid, domains in alloweddomains.items %}
{% if listtestcase.id == testcaseid %}
{% for key, value in domains.items %}
<div><a class="sendtolinkdisabled" data-testcasename="{{ listtestcase.name }}" data-testcaseid="{{ $
{% endfor %}
{% endif %}
{% endfor %}
This basically looped through the dictionary and if there was a match to my unique ID I get the data and do something with it
I tried various ways to not need the if statement and just get the right point in the dictionary, but nothing seemed to work (so I took the if approach)
Grant

display list value in template page using django

I need to display the value of list in template page using django. I have a variable like
data = [('dic1',),('dic2',)]
I pass the value to the template this way:
return render(request,'success.html',{'details':data})
Then in the template I need to show the value. I have used the for loop in the template like:
{% for a in data %}
{{a}}
{% endfor %}
But it displays as
('dic1',)
('dic2',)
when I need to display only the value like below
dic1
dic2
Canyone help me to find out which mistake I did ?
Thanks for your response. I jus to use like below
{% for a in data %}
{{ a.0 }}
{% endfor %}
Now it's working correctly.

python/django for loop and list attributes

So, i'm studying the Django Book, and django documentation, and I can't understand this example:
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
This is about templates and i don't how to code the Context. How can i get attribute called "name" from a list ? If i create a dictionary it will be impossible to use for loop like in this example. I have coded it like this but it's not working:
athlete_list = {'name' = ['Athlete1', 'Athlete2', 'Athlete3']}
Context({'athlete_list':athlete_list})
if i change athlete_list variable to a normal list (not a dictionary) the "athlete.name" in the template won't work too. I don't think it's a mistake in a book, and it's probably very easy to solve, but i can't get it.
I'd suspect that athlete_list is a QuerySet object containing Athlete models... (does that get mentioned anywhere?). The models will then have a .name or .age or .sport or whatever...
update - just looked at http://www.djangobook.com/en/2.0/chapter04.html - which actually doesn't appear to be the best example....
To keep the template as is, you can return a context of a list of dicts, eg:
[ {'name': 'bob'}, {'name': 'jim'}, {'name': 'joe'} ]
If you want to keep the template,you should return below.
athlete_list = ({'name':'Athlete1'},{'name':'Athlete2'},{'name':'Athlete3'})
Context({'athlete_list':athlete_list})
Your athlete_list is actually a dict
<ul>
{% for athlete_name in athlete_list.name %}
<li>{{ athlete_name }}</li>
{% endfor %}
</ul>
in templates you can access dictionary keys through . instead of through []
so in your template {{ athleate_list.name }}
would be a list of strings # ['Athlete1', 'Athlete2', 'Athlete3']

Can I access specific key values in dictionary from django template?

Is there any get() function for this instead?
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
From python I have the get() function to get values from a specific key. But I couldn't find a corresponding way to do that with django template tags. So I wonder is it possible?
I need to get specific values since using loops adds a lot of new lines in the html source.
Or should take care of the output inside the view before sending it out to the template, which method is better?
You can use {{ choices.items.key }} to access a specific dict element.
There is no reason to care about whitespace in the HTML code though; the typical end-user has no real business in reading it and if he's curious he an always use a DOM viewer or run it through a HTML beautifier.
If you want a specific value, just add it to the dotted-path:
{{ choices.items.somekey }}
will get you the value of choices.items['somekey'] if choices.items is a dict.
I think you are way advance now, just to share my point. you could do this way as well
{% for value in dict %}
{{value}}
{% endfor %}
or with key, value like
{% for key,value in dict.items %}
{{key}} : {{ value }}
{% endfor %}
If choices type is DICT like {}.
{{choices.somekey|default:""}}
If choices.items is DICT type.
{{choices.items.somekey|default:""}}
Try See little example.
# In Views.py
def dict_test(request):
my_little_dict = {"hi": "Hello"}
....
# in Template
{{my_little_dict.hi}}
You can specify as {{ choices.key_name }}
It worked for me. Just simple
{{ choices.values }}
This gives you a list of all the values in the dictionary at once.

Categories