简体   繁体   中英

Django dict key,value in for loop does not work

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

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 .

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM