[Answered ]-Give values to each form in a formset in Django

2👍

You can write a custom formset.

from django.forms.formsets import BaseFormSet

class TagFormSet(BaseFormSet):

    def __init__(self, *args, **kwargs):
        applicants = kwargs.pop('applicants')
        super(TagFormSet, self).__init__(*args, **kwargs)
        #after call to super, self.forms is populated with the forms

        #associating first form with first applicant, second form with second applicant and so on
        for index, form in enumerate(self.forms):
            form.applicant = applicants[index]

Now you don’t need to override __init__ of TagsForm.

Now each of your form is associated with an applicant. So, you can remove the first line of your saveTags(). So saveTags() become:

def saveTags(self):
    #applicant was set on each form in the init of formset
    Tag.update(self.applicant, tags)

Your view code:

applicantQuery = allApplicantsQuery.filter(**kwargs)

#notice we will use our custom formset now
#also you need to provide `extra` keyword argument so that formset will contain as many forms as the number of applicants
TagsFormSet = formset_factory(TagsForm, formset=TagFormSet, extra=applicantQuery.count())

if request.method == 'POST':
    tags_formset = TagsFormSet(request.POST, request.FILES, prefix='tags', applicants=applicantQuery)
    if tags_formset.is_valid()
        for tagForm in tags_formset:
            tagForm.saveTags()
else:
    tags_formset = TagsFormSet(prefix='tags', applicants=applicantQuery)

Leave a comment