How do I pass an item and an associated formset from the view to the template in Django?

I understand how to pass multiple items in the views to the template, you just pass multiple items in the context.

I'm trying to learn to build a checklist app for learning and to have a formset for links associated to each item to learn. So you can like save multiple youtube instructional links to each item.

But let's say that I am passing query of items over. And for each item has a formset created for it. How do I pass over the associated formset over with the item?

Thru using chatgpt and google, I've come up with this

def currentchecklist(request):
    items = Item.objects.filter(user=request.user, datecompleted__isnull=True)
    courses = request.user.checklist_courses.all()
    LinkFormSet = inlineformset_factory(Item, Link, fields=('url',), extra=1)

    formsets = [] 
   
    for item in items:
        formsets.append((item, LinkFormSet(instance=item)))

    return render(request, "BJJApp/currentchecklist.html", {"items": items,"courses": 
    courses, "formsets": formsets})

and then in the template, I have this

{% for item, formset in formsets %}
 <div class="formset" id="linkform-{{ item.id }}" style="display: none;">
     <label for="title">Links for {{ item.title }}</label>
     
           {{ formset.as_p }}
                           
     </div>

This code works so far to display the formset, I'm next working on saving the links.

I just wanted to ask, is this the best way to access the item and associated formset? By using the list of tuples? Or is there a better way?

Thanks!

Back to Top