Having trouble in Django final project supplying context from an array to a View and accessing context array elements based on some counter variable within template?

Hi all,
I may well be approaching the problem in entirely the wrong way but to try and summarize concisely:

I’ve more or less completed The Django Delights final project and been busy putting in extra functionality and implementing my own take on the theme suggested (I went for a Magic Potion Shop selling dodgy potions because more fun than a restaurant, anyway…).

I’m trying to implement a template view for authenticated users that displays a list of ingredients and respective costs for each potion with a total cost displayed at the end of each iteration through the Potion Item View.

So, I am able to populate an array of total costs for each Potion Item and then supply this array as context to the template. Within the template I thought I would try and use the built in {{ forloop.counter0 }} and use that value to access the total cost for that particular potion at given index thus… {{ total_cost.forloop.counter0 }}

I can display the whole array as just {{ total_cost }} but that’s no use for what I’m trying to do. I’ve tried using the {% with %} tag too to no avail. I’m obviously approaching the problem in the wrong way but confused as to how to I can use a counter within a template to access indexes in an array supplied from the context?

Here’s my code from ‘views.py’…

class PotionView(LoginRequiredMixin, ListView):

    template_name = "magicshop/potion_list.html"

    model = PotionItem

    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)

        total_array = []

        for potion in PotionItem.objects.all():
            total_cost = 0
            for requirement in potion.reciperequirement_set.all():

                total_cost += requirement.req_cost()

            total_array.append(total_cost)

            
        context["total_cost"] = total_array

        return context

and then within ‘potion_list.html’ I thought I’d try and do this…

<p>Total cost in ingredients : {{ total_cost.forloop.counter0 }}</p>

I’m iterating through the ‘potion’ instances of ‘PotionItem’. This line is just before end of each iteration. Because context is returned from outside of the for loops, I’m struggling with how to dynamically access array elements within template itself.

Hoping I’ve explained myself properly and somebody can help. I’ve been looking on StackOverflow and the like and as far as I can tell, {{ forloop.counter0 }} should be able to help me?

I’ve tried a dictionary approach…
in my PotionView…

def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)

        total_array = []

        profit_array = []

        total_dict = {}

        

        for potion in PotionItem.objects.all():

            total_cost = 0

            for requirement in potion.reciperequirement_set.all():

                total_cost += requirement.req_cost()

            total_array.append(total_cost)

            profit_array.append(round(potion.price - total_cost, 2))

            total_dict[potion.id] = {'total_cost':total_cost, 'profit_cost':round(potion.price - total_cost, 2)}

        context["total_cost"] = total_array

        context["profit"] = profit_array

        context["total_dict"] = total_dict

        return context

and I’ve rendered {{ total_dict }} in my template and know it looks correct with each potion id having a total cost and profit attached but again same problem of accessing the value in template…

<p>Total cost in ingredients : {{ total_dict.potion.id.total_cost }}</p>

displays nothing and

<p>Total cost in ingredients : {{ total_dict[potion.id].total_cost }}</p>

or

<p>Total cost in ingredients : {{ total_dict.'potion.id'.total_cost }}</p>

displays an error (Unable to parse remainder…)! Again, how can I access and render each instance within the dictionary supplied by context?

Solved It… Yippee!!
Solution -

{% for key, value in total_dict.items %}

            {% if key == potion_item.id %}

            <p>Total cost in ingredients :  {{ value.total_cost }}</p>

            <p>Profit* :  {{ value.profit_cost }}</p>

            {% endif %}

            {% endfor %}

Should I leave thread here or remove it? Sometimes one can’t see the wood because of all the trees. In retrospect this solution is blindingly obvious. Doh!
I gleaned the answer from StackOverflow and problem has been addressed a million times before :slight_smile: