0

I have a context variable that contains a dictionary, which was created via defaultdict(list).

The dictionary's anatomy is like so:

eachlink = {'seen':[object1, object2, None], 'unseen':[None, object2, object3], 'time':[timeobject1, None, timeobject3]}

'seen', 'unseen' and 'time' are lists containing objects (and an object can be None too).

This dictionary is passed to the context object in views.py:

context["eachlink"] = eachlink

In my template, I'm trying to use the data contained within the context variable eachlink, but can't get the dot notation to work. E.g. the following does NOT work (the for loop never runs, nor the if statement ever fires):

{% for object in eachlink %}
{% if object.seen %}
do something
{% endif %}
{% if object.unseen %}
do something else
{% endif %}
{% if object.time %}
do something else
{% endif %}
{% endfor %}

I also tried the following, which didn't work:

{% for seen, unseen, time in eachlink %}
{% if seen %}
do something
{% endif %}
{% endfor %}

In the above, debugging led me to the finding that 'seen' contains the letters 'seen', unseen contains the letters 'unseen' and time contains the letters 'time'. Clearly, the lists within the dictionary aren't being referenced. I've seen suggestions on SO to use eachlink.items instead of eachlink, I've also seen suggestions to write custom templatetags. Both approaches haven't fit my case after multiple hours of trying.

I've printed my dictionary via views.py; it's being constructed fine. Accessing it in the template remains a challenge. What should I do? Should I pursue an alternative way to organize this data in my context variable? Suggestions please.

I'm using Django 1.5 and Python 2.7.

Hassan Baig
  • 15,055
  • 27
  • 102
  • 205
  • See also the explanation on [this answer](http://stackoverflow.com/questions/10705669/my-defaultdictlist-wont-show-up-on-template-but-does-in-my-view/10705819#10705819). – Alasdair Oct 18 '15 at 19:26
  • Thanks for the quick turnaround buddy, going through your suggestions. – Hassan Baig Oct 18 '15 at 19:38
  • @Alasdair I have a question. I've made some headway, but I'm unable to use `object` from `{% for object in eachlink.items %}`. However, I'm instead able to use `object.1`. And `object.1.1`, `object.1.2` etc refers me to various content within `object`. It's quite peculiar and unreadable for me right now. – Hassan Baig Oct 18 '15 at 20:31
  • 1
    Firstly, make sure you converted the default dict to a regular dict, or followed the other suggestion in the linked answer. Note that items returns pairs of keys and values, so you need to do `{% for key, value in eachlink.items %}`. Then you can use `{{ key }}` and `{{ value }}`. – Alasdair Oct 18 '15 at 21:04
  • Thanks man, works nicely. `object.1` was pointing to `value`. It's much more readable now. Kudos :-) – Hassan Baig Oct 18 '15 at 21:14

0 Answers0