Display of dictionary in django - python

My List
book_details = [
{'author':'abc', 'book_name':'xyz', 's_no':1},
{'author':'efg', 'book_name':'ijk', 's_no':2}
]
My code:
{% for dict in details %}
<tr>
{% for key, value in dict.items %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
Output :
Author Book_name S_no
Desired output:
S_no Book_name Author
I'm new to django , please guide.

Right now you are iterating through each key-value pair in the dictionary, so your code is outputting dictionary values in the order in which they are stored in the dictionary, which happens to be:
Author Book_name S_no
So, you have two options.
Change the order in which these attributes are stored in the dictionary. If you change the structure of your dictionaries from {'author': 'abc', 'book_name':'xyz','s_no':1} to {'s_no':1, 'book_name':'xyz', 'author': 'abc'}, iterating over the key-value pairs will return these attributes in the desired order. However, this is not a very flexible solution, so I would suggest the second option.
Change the way you output dictionary values. Instead of iterating through all the key-value pairs in whatever order they happen to be in, you can explicitly define the order in which you want to output dictionary values by changing this:
{% for key,value in dict.items %}
<td>{{value}}</td>
{% endfor %}
to this:
{% for key in ['S_no', 'Book_name', 'Author'] %}
<td>{{dict[key]}}</td>
{% end for %}
This solution has the added benefit of being quite easy to modify if, later on, you decide you want to output these values in another order.

{% for dict in details %}
<tr>
<td>{{dict.s_no}}</td>
<td>{{dict.book_name}}</td>
<td>{{dict.author}}</td>
</tr>
{% endfor%}

Related

Trouble with python dictionaries and iterating through them with Jinja

I have a Python dictionary that looks like this. {0: {'record': u'running fast', 'moreInfo': u'test', 'year': u'2017', 'name': u'Jose la computadora', 'activity': u'Cross Country'}, 1: {'record': u'test', 'moreInfo': u'ttt', 'year': u'2000', 'name': u'Lewdog', 'activity': u'Cross Country'}}
I'm passing it to a Jinja template with Flask. The dictionary is set to the variable databaseQuery and passed to Jinja.
My jinja code looks like this, but nothing shows up on the page.
If I print databaseQuery on the page, I get the whole dictionary, and if I print test, I just get 0 1.
I'm trying to figure out how to iterate through my dictionary and show each value for name on the page.
{% for test in databaseQuery %}
{{test["name"]}}
{% endfor %}
I've looked at this list of dictionary in jinja template but didn't have any luck.
Thanks!
Well you're just iterating through the keys of databaseQuery.
Jinja suppresses some errors so that's why it's not exploding for you.
This isn't a Jinja issue but a python issue; if you iterate through a dictionary without specifying keys, values or items, it'll just loop through the keys, which for you are 0 and 1 which are just integers.
If you want to access just the values, you could do
{% for val in databaseQuery.values() %}
{{ val['name'] }}
{% endfor %}
should get you what you want. It's worth noting unless those integers (0 and 1) will be used for something meaningful, you could just pass up the list of dictionaries and loop through that as you did and that would work.
Iterating a dict produces only the keys. You can do:
{% for k in databaseQuery %}
{{ databaseQuery[k]['name'] }}
{% endfor %}
Or:
{% for k, v in databaseQuery.items() %}
{{ v['name'] }}
{% endfor %}
Hei ;
With python iterating over a dict gives you the key.
a = {1:'test'}
for k in a
will give you 1
Try a[key] to access the values
Edit :
{% for test in databaseQuery %}
{{databaseQuery[test]}}
{% endfor %}

Dynamic number of columns in Django template

I have recently tried to solve the challenge of handling a dynamic number of columns in my Django template (essentially working through a list containing lists that isnt standerdized).
I pass two things to my view:
test_array: an array that looks something like the following [[1,2,3],[1,2,3],[1,2,3]]
numbers: in this case 3 (indicating the number of attributes in the sub lists
I thought to solve this as follows:
<tbody>
{% for t in test_array %}
<tr>
{% for x in numbers %}
<td>{{ t.x }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
But the above returns no output. When I reference t.1, t.2 etc hardcoded this returns output.
As such, what is the best way to handle a dynamic number of columns in Django? Or, is there a more elegant way to solve the above?
Passing the length of the sublists to the the template isn't necessary.
As the list elements are also lists the inner loop could simply be reduced to this:
{% for x in t %}
<td>{{ x }}</td>
{% endfor %}

How to do this in Jinja2?

Hello I am using jinja2 and I have a list of dictionaries that I am passing to jinja template.
{%for dict in list_of_dicts%}
<tr>
{%for key in my_dict.keys()%}
<td> {{my_dict.key}}</td> // Here i want to get value in my_dict with that particular key.
{%endfor%}
</tr>
{%endfor %}
How do I achieve this?
By using just one variable in your for-loop, you just get the value and not the key name. You can use the alternative key, value syntax (as documented here) in a for loop to get the keys in a separate variable, like this:
{% for key, value in my_dict.iteritems() %}
<td>{{ key }}</td>
{% endfor %}

iterating through list with floor loop jinja django python

I have this array:
scores = [45.62, 51.87, 33.12, 39.37, 33.12]
I want to iterate through the list, and pass each item to an html template.
Using jinga, i tried the following:
{% for items in scores %}
{‌{ items }}
<br>
{% endfor %}
I hoped that the above would print out each item in the list like so:
45.62
51.87
33.12
etc...
but it didn't, it just prints the entire list, as a list, on one line.
I also tried this:
{% for items in scores %}
{‌{ scores.0 }}
<br>
{% endfor %}
This printed out just the first score of the list, but not the others. I want to print out each score individually. Please help! I'm using django 1.9. I know this is jinja, not sure if it's jinja2?
Feels like list is not as you put in question.Try this
{% for items in scores.0 %}
{‌{ items }}
<br>
{% endfor %}
Try changing up the variable names. Maybe you have another variable called items in your context. It would make more sense to use a variable name that's not plural for the loop.
{% for score in scores %}
{‌{ score }}
<br>
{% endfor %}

How to use django template dot notation inside a for loop

I am trying to retrieve the value of a dictionary key and display that on the page in a Django template:
{% for dictkey in keys %}
<p> {{ mydict.dictkey }} </p>
{% endfor %}
(let's say 'keys' and 'mydict' have been passed into the template in the Context)
Django renders the page but without the dictionary contents ("Invalid template variable")
I assume the problem is that it is trying to do mydict['dictkey'] instead of mydict[actual key IN the variable dictkey]? How does one "escape" this behavior?
Thanks!
UPDATE:
Based on the answers received, I need to add that I'm actually looking specifically for how to achieve a key lookup inside a for loop. This is more representative of my actual code:
{% for key, value in mydict1.items %}
<p> {{ mydict2.key }} </p>
{% endfor %}
Basically, I have two dictionaries that share the same keys, so I can't do the items() trick for the second one.
See this answer to a (possibly duplicate) related question.
It creates a custom filter that, when applied to a dictionary with a key as it's argument, does the lookup on the dictionary using the key and returns the result.
Code:
#register.filter
def lookup(d, key):
if key not in d:
return None
return d[key]
Usage:
{% for dictkey in dict1.keys %}
<p> {{ dict2|lookup:dictkey }} </p>
{% endfor %}
Registering the filter is covered in the documentation.
I find it sad that this sort of thing isn't built in.
From http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
The trick is that you need to call dict.items() to get the (key, value) pair.
See the docs: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}

Categories

Resources