-1

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.

jape
  • 2,861
  • 2
  • 26
  • 58

2 Answers2

0

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.

  1. 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.

  2. 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.

  • I tried your method, I'm getting this error. Could not parse the remainder: '['s_no','book_name','author']' from '['s_no','book_name','author']' – Gautam Lal Jul 26 '16 at 07:38
  • {% for dict in details %} {{dict.s_no}} {{dict.book_name}} {{dict.author}} {% endfor %} This worked for me. – Gautam Lal Jul 26 '16 at 10:47
0
{% for dict in details %}
                <tr>
                    <td>{{dict.s_no}}</td>
                    <td>{{dict.book_name}}</td>
                    <td>{{dict.author}}</td>

                </tr>

{% endfor%}