简体   繁体   中英

Access dictionary in Django template

I have a property in the Circuit model which calculates for each Diameter the corresponding total pipe length for that diameter. The code is given below:

@property
def pipe_lengths(self):
    components = Component.objects.filter(circuit=self)
    diameters = Diameter.objects.filter(project=self.system.project, material = self.material_type)

    pipe_dict = {}
    length = 0
    for diameter in diameters:
        for component in components:
            if component.diameter == diameter: 
                length += component.length
        pipe_dict[diameter] = length
        length = 0

    print("PIPE_DICT IS: " + str(pipe_dict))
    return pipe_dict

This seems to work fine, the output of the print statement seems okay. However now I want to access this dictionary in my template, below is the simplified code I already have:

{% extends 'base.html' %}

{% block content %}
<h2>Circuit name: {{ circuit.circuit_name }} 

<h3><strong>Piping lengths</strong></h3>
<table border="1" style="width:100%">
  <tbody>
    <tr>
      <td><h3>nominal diameter</h3></td>
      <td><h3>length [m]</h3></td>
    </tr>
    {% for diameter in circuit.pipe_lengths %}
    <tr>
      <td><h3>{{ diameter.nom_diameter }}</h3></td>
      <td><h3>{{ circuit.pipe_lengths[diameter] }}</h3></td>
    </tr>
    {% endfor %}

  </tbody>
</table>

{% endblock %}

I can access the

diameter.nom_diameter .

However when I try to access the specific length-value by the code:

circuit.pipe_lengths[diameter]

this does not work. I get the following error:

TemplateSyntaxError at /solgeo/28/system/182/circuit/295/
Could not parse the remainder: '[diameter]' from 'circuit.pipe_lengths[diameter]'

Help is very much appreciated.

Simply

{% for diameter, length in circuit.pipe_lengths.items %}
<tr>
  <td><h3>{{ diameter.nom_diameter }}</h3></td>
  <td><h3>{{ length }}</h3></td>
</tr>
{% endif %}

should do.

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