76
it would be best if you construct your data like {note the β(β and β)β can be exchanged for β[β and β]β repectively, one being for tuples, one for lists}
[ (Product_Type_1, ( product_1, product_2 )),
(Product_Type_2, ( product_3, product_4 )) ]
and have the template do this:
{% for product_type, products in product_type_list %}
{{ product_type }}
{% for product in products %}
{{ product }}
{% endfor %}
{% endfor %}
the way tuples/lists are unpacked in for loops is based on the item returned by the list iterator.
each iteration only one item was returned. the first time around the loop, Product_Type_1, the second your list of productsβ¦
104
Another way is as follows.
If one has a list of tuples say:
mylst = [(a, b, c), (x, y, z), (l, m, n)]
then one can unpack this list in the template file in the following manner.
In my case I had a list of tuples which contained the URL, title, and summary of a document.
{% for item in mylst %}
{{ item.0 }} {{ item.1}} {{ item.2 }}
{% endfor %}
- [Django]-Simple guestbook django: __init__() takes 1 positional argument but 2 were given
- [Django]-DatabaseError: current transaction is aborted, commands ignored until end of transaction block?
- [Django]-Sort order of Django Admin records
10
You must used this way:
{% for product_type, products in product_list.items %}
{{ product_type }}
{% for product in products %}
{{ product }}
{% endfor %}
{% endfor %}
Donβt forget the variable items in the dictionary data
- [Django]-How to customize user profile when using django-allauth
- [Django]-Where can I find the error logs of nginx, using FastCGI and Django?
- [Django]-">", "<", ">=" and "<=" don't work with "filter()" in Django
3
If you have a fixed number in your tuples, you could just use indexing. I needed to mix a dictionary and the values were tuples, so I did this:
In the view:
my_dict = {'parrot': ('dead', 'stone'), 'lumberjack': ('sleep_all_night', 'work_all_day')}
In the template:
<select>
{% for key, tuple in my_dict.items %}
<option value="{{ key }}" important-attr="{{ tuple.0 }}">{{ tuple.1 }}</option>
{% endfor %}
</select>
- [Django]-Best way to integrate SqlAlchemy into a Django project
- [Django]-Simple guestbook django: __init__() takes 1 positional argument but 2 were given
- [Django]-New url format in Django 1.9
2
Just send the template a list of product types and do something like:
{% for product_type in product_type_list %}
{{ product_type }}
{% for product in product_type.products.all %}
{{ product }}
{% endfor %}
{% endfor %}
Itβs been a little while so I canβt remember exactly what the syntax is, let me know if that works. Check the documentation.
- [Django]-Django: how to do calculation inside the template html page?
- [Django]-Execute code when Django starts ONCE only?
- [Django]-Navigation in django