Using an object attribute when accessing element in array in Django Template Python

So basically in my Django template I'm passing in two things from my view.

  1. a Django model object Plan which is defined like:
class Plan(models.Model):
    class Sport(models.IntegerChoices):
        RUN = 1, "RUNNING"
        CYC = 2, "CYCLING"
        SWM = 3, "SWIMMING"

    sport = models.PositiveSmallIntegerField(
        choices=Sport.choices,
        default=Sport.RUN
    )

    start_date = models.DateField("Starting Date")
    end_date = models.DateField("End Date")
    weeks = models.PositiveSmallIntegerField(default=0)
    
    title = models.CharField(max_length=20)
    description = models.TextField(max_length=100, blank=True, null=True)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

and 2. an array of arrays of strava activities pulled from an API, activity_list which is formatted so activity_list[i][j] would return week i's activity on day j.

In my template, I need to access activity_list dynamically whilst looping through the week numbers in the plan. My first attempt was to do something like ativity_list.week.number.0 to access the Monday of the week we're on, but as expected Django treats week.number as a literal instead of replacing it with the number "0" or "3" or whatever.

I'm really stuck on this so any help would be much appreciated, either with an ad-hoc fix or a way to refactor my models to make this feasible.

Thanks

So this is actually the same question as this: Get list item dynamically in django templates

Basically use a filter like

@register.filter
def lookup(d, key):
    return d[key]

and then use {% with lookup_result=mylist|lookup:x %}{{lookup_result.first_name}}{% endwith %}

Back to Top