简体   繁体   中英

How to create a local variable in a html template in django project?

I am a beginner to python and django. Here I am trying to build a website.

I have created a class named cluster which actually mean a town or city. As a subclass I have created schools for cluster. Schools have a field school_strength to get strength for each school. Now I have to display the total strength of all the schools that belong to each cluster.

This is how I am trying to do that in html template for cluster details by creating a local variable strength to calculate sum from all schools.

<div class="col-sm-4 col-md-3">
        <div class="panel panel-default">
            <div class="panel-body">
                <a href="{% url 'music:cluster_detail' state.id region.id cluster.id %}">
                    {% if cluster.cluster_logo %}
                        <img src="{{ cluster.cluster_logo.url }}" class="img-responsive">
                    {% else %}
                        <h3>No image to display</h3>
                    {% endif %}
                </a>
                <h2>{{ cluster.cluster_name }}</h2>
                <h4>{{ cluster.cluster_coordinator }}</h4>
                <h4>{{ cluster.cco_number }}</h4>
                <h4>{{ cluster.cco_email }}</h4>
                {% for school in cluster.school_set.all %}
                    {% strength = strength + school.school_strength %}
                {% endfor %}
                <h4>{{ strength }}</h4>
            </div>
        </div>
    </div>

I think you can declare the variable with with tag. But that will not work the the way you want it to work . Below is an example to it.

{% with name="World" greeting="Hello" %}     
    <h1>{{ greeting }} {{name}}!</h1>
{% endwith %}

So, the better way is you can store it in a variable in views.py and pass it to html template.

views.py

strength=0
for school in cluster.school_set.all():
     strength = strength + school.school_strength

context['strength']=strength

return render(request, 'template/html`, context)

html

<h3>Strength Of Cluster: {{strength}}</h3>

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