FormSet with class-based views

Hi everyone! I have a doubt about using formset with class-based views, that may be simpler, but i couldn’t figured out so far.

I have the following models:

class ProjectModel(models.Model):
 charcode = models.Charfield(unique=True)

class QuestionModel(models.Model):
 title = models.Charfield()
 type = models.CharField(choices=('text','rate'))

class SurveyModel(models.Model):
 project = models.ForeignKey(ProjectModel)
 active = models.BooleanField(default=False)
 questions = models.ManyToManyField(QuestionModel)

class AnswerModel(models.Model):
 question = models.ForeignKey(QuestionModel)
 response_text = models.TextField()
 response_rate = models.IntegerField(choices=(1,2,3,4,5))

class SubmissionModel(models.Model):
 user = models.ForeignKey(get_user_model())
 survey = models.ForeignKey(SurveyModel)
 answers = models.ManyToManyField(AnswerModel)

I need a view to render **questions** of a active **survey** so a user can fill it in a form that will create **answers** objects and a **submission** object.

so, I have this url:
path('submission/<str:charcode>/, SubmissionView.as_view())

this view that receives **charcode** from url:

class SubmissionView(CreateView):
 form_class = SubmissionFormSet

and this formset (in construction):

class SubmissionFormSet(form.BaseFormSet):
 # need to get questions from survey_objects.get(project__charcode = 'charcode', active=True)
 # define each field based on question type to properly widget choice
 # save answers and submission based on responses from user

i really have no idea yet, but i guess i must use formset_factory, maybe inside view like **AnswerFormset = formset_factory(AnswerForm, formset=SubmissionFormSet)** but not sure to be honest

There are a couple things I’ve found to be helpful to keep in mind when working with formsets.

  • A formset can be thought of as a “list of forms” that can be worked on as a group. So if you would want to create “n” number of instances of a particular form and put them in a list - that’s a formset.

  • A formset_factory creates a formset Class - not an actual formset. You create the formset by making an instance of that class. It’s similar in principle to defining a form. You create a form class in your, then create the instances of that form in your views. The difference is you don’t defined a formset as class MyFormset, you define it as MyFormset = formset_factory(...). You still need to create the formset to be used. (e.g. my_formset = MyFormset(…)`)

  • The formset is “lazy”. The instances of the individual forms are not created when the formset is create. Those forms aren’t created until the first time they’re “needed”. This means you have the ability to alter that formset after being created but before being used.

Personally, I found reading the source code for formsets to be very helpful with understanding how they work.