【问题标题】:Access Dictionary Value inside list in Django Template在 Django 模板中访问列表中的字典值
【发布时间】:2018-09-11 13:56:03
【问题描述】:

我在列表中有一本字典。我想访问 django 模板中的字典值。我怎么能得到那个? 视图.py

def payment_status(request):
    l1=[]
    cand = CandidateDetail.objects.all()


    for person in cand:
        for num in range(0,paid['count']):
            if paid['items'][num]['email']==person.email and paid['items'] 
            [num]['status']=='authorized':
                cand_dict = {'first_name':person.first_name, 
                'last_name':person.last_name, 'email':person.email, 
                 'paid':'Yes'}
                l1.append(cand_dict)


    return render(request, 'desk/payment_status.html',{'cand_list':l1})

html文件

<div class="col-md-10">
      <h3>Candidate Payment Status</h3>
      <table class="cand_list">
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Payment Status</th>
        </tr>

        {% for candidate in cand_list %}
      <tr>
        <td>{{ candidate.first_name }} {{ candidate.last_name }}</td>
        <td>{{ candidate.email }}</td>
        <td>{{ candidate.paid }}</td>
      </tr>
    {% endfor %}
      </table>
</div>

我得到的错误是 -- 无法解析余数:'[item]['first_name']' from 'cand_list[item]['first_name']'

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    首先,在某个长度范围内迭代永远是正确的做法——无论是在 Python 中还是在模板中。

    其次,在 Django 模板语言中,您总是使用点表示法,即使对于字典键也是如此。

    所以,在你看来:

    for person in cand:
        for item in paid['items']:
            if item['email']== person.email and item['status']=='authorized':
                 ....
    

    在你的模板中:

        {% for item in cand_list %}
        <tr>
          <td>{{ item.first_name }} {{ item.last_name }}</td>
          <td>{{ item.email }}</td>
          <td>{{ item.paid }}</td>
        </tr>
        {% endfor %}
    

    【讨论】:

      【解决方案2】:

      您不需要 cand_len 列表,只需遍历 cand_list(dict 列表)并使用 dict 键访问。

      <div class="col-md-10">
            <h3>Candidate Payment Status</h3>
            <table class="cand_list">
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Payment Status</th>
              </tr>
      
              {% for item in cand_list %}
              <tr>
                <td>{{ item.first_name }} {{ item.last_name }}</td>
                ..
                ..
              </tr>
              {% endfor %}
            </table>
      </div>
      

      【讨论】:

      • 感谢@Verma PK 的帮助
      【解决方案3】:

      你可以使用 {{ mydict.key }}

      docs

       {% for candidate in cand_list %}
          <tr>
            <td>{{ candidate.first_name }} {{ candidate.last_name }}</td>
            <td>{{ candidate.email }}</td>
            <td>{{ candidate.paid }}</td>
          </tr>
          {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 2016-02-29
        • 2014-02-08
        • 2021-10-17
        • 2015-08-18
        • 1970-01-01
        • 2021-10-17
        • 2011-07-11
        相关资源
        最近更新 更多