For loop in Django template causing error when I use the add filter

Viewed 73

I am trying to add two variables together in my template that will combine two scores together and print the value. The problem is when the loop gets to a game that hasn't happened yet it kicks out an error because the variable doesn't exist yet.

What am I supposed to add to skip games in the loop that have no score?

    {% for game in games %}
        <p class="light-blue text-center">
            Total: {{ game.scoreboard.score.home|add:game.scoreboard.score.away }}
        </p>
    {% endfor %}
1 Answers

I would advice to implement this in the model, not in the template.

So if you have a model for Score for example, you can implement this as:

class Score(models.Model):
    home = models.IntegerField()
    away = models.IntegerField()
    
    @property
    def total(self):
        return self.home + self.away

and then render this as:

{% for game in games %}
    <p class="light-blue text-center">
        Total: {{ game.scoreboard.score.total }}
    </p>
{% endfor %}

If the data is is a structure of dictionaries. You can preprocess this in the view with:

def my_view(request):
    # … some data …
    for game in data['games']:
        score = game['scoreboard']['score']
        score['total'] = score['home'] + score['away']
    # …

if not all games have a scoreboard, you can first check if that is an element of the dictionary:

def my_view(request):
    # … some data …
    for game in data['games']:
        if 'scoreboard' in game and 'score' in game['scoreboard']:
            score = game['scoreboard']['score']
            score['total'] = score['home'] + score['away']
    # …
Related