1

I'm getting a little stuck on a Django problem where I can't access the values of a dict in a for loop. It works outside the for loop, just not inside.

Am I missing the obvious here?

Python:

err{}
err['else'] = {'class': 'Low', 'txt': 'zero'}
err['if'] = {'class': 'High', 'txt': 'one'}
data = { 'errors': err }
return render(request, 'index/error.html', data)

HTML template:

<p>{{ errors }}</p>
<p>{{ errors.if }}</p>
<p>{{ errors.if.class }}</p>

{% for error in errors %}
  <div class="{{ error.class }}"><p>{{ error.txt }}</p></div>
{% endfor %}

The upper 3 lines are for code debugging and work just fine. The for loop doesn't produce any code.

Best regards, LVX

LVX
  • 97
  • 7

3 Answers3

9

You probably need to access .items() of the dict that you called errors. Just iterating over a dict gives you the keys, but not the values.

You can change your code to:

{% for k, v in errors.items %}
  <div class="{{ v.class }}"><p>{{ v.txt }}</p></div>
{% endfor %}

Of course, if you don't need the keys (if and else) then you could also use .values() instead of items() to just get the values inside the dict.

Ralf
  • 16,086
  • 4
  • 44
  • 68
  • Thanks Ralf, that did the trick. I find it an odd way, but if you look at the code it somehow makes sense. – LVX Dec 29 '18 at 12:27
  • Can you please provide an example where do not know the key information eg: class or txt? – Sade Jun 28 '21 at 08:33
2

The answer by Ralf is sufficient for the question, I just want to add an extra piece of information here.

When the template system encounters a dot in a variable name, it tries the following look-ups, in this order:

  1. Dictionary Lookup (eg: foo['bar'])
  2. Attribute Lookup (eg: foo.bar)
  3. Method Call (eg: foo.bar())
  4. List-Index Lookup (eg: foo[2])

The system uses the first lookup type that works.

0

You should try like this - error['class']

Second way - error[key]['class']

Use forloop - for k,v in errors: print(v['class'])

Rohit Garg
  • 71
  • 2
  • 8
  • Rohit: to my understanding of Django that is not allowed. correct me if I'm wrong. – LVX Dec 29 '18 at 12:29
  • @RohitGarg you cannot use brackets for access in `Django` templates. See also [this answer](https://stackoverflow.com/a/19745156/9225671) – Ralf Dec 29 '18 at 12:37