相关疑难解决方法(0)

Django模板如何使用变量查找字典值

mydict = {"key1":"value1", "key2":"value2"}
Run Code Online (Sandbox Code Playgroud)

在Django模板中查找字典值的常规方法是{{ mydict.key1 }}, {{ mydict.key2 }}.如果键是循环变量怎么办?即:

{% for item in list %} # where item has an attribute NAME
  {{ mydict.item.NAME }} # I want to look up mydict[item.NAME]
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

mydict.item.NAME失败.如何解决这个问题?

python django templates dictionary

207
推荐指数
4
解决办法
12万
查看次数

Django dict键,for循环中的值不起作用

我有点卡在Django问题上,我无法在for循环中访问dict的值.它在for循环之外工作,而不是在内部.

我错过了明显的吗?

蟒蛇:

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

HTML模板:

<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 %}
Run Code Online (Sandbox Code Playgroud)

上面3行用于代码调试,工作得很好.for循环不会产生任何代码.

最好的问候,LVX

python django dictionary key

1
推荐指数
1
解决办法
236
查看次数

标签 统计

dictionary ×2

django ×2

python ×2

key ×1

templates ×1