Home > Net >  Django MultiModelFormView
Django MultiModelFormView

Time:09-15

I am using django-multi-form-view to display 2 model forms on the same page. I have a parent model and a student model. Student has a foreign key to parent, as I can have many children per parent. ( one to many relationship)

models.py

class Parent(models.Model):
    p_first_name = models.CharField(max_length=255)
    p_last_name = models.CharField(max_length=255)
    email = models.EmailField(unique=True)
    
    def __str__(self):
        return f'{self.p_first_name} {self.p_last_name}'


class Student(models.Model):
    s_first_name = models.CharField(max_length=255)
    s_last_name = models.CharField(max_length=255)
    parent = models.ForeignKey('Parent', on_delete=models.CASCADE)

    def __str__(self):
        return f'{self.s_first_name} {self.s_last_name}'

forms.py:


class ParentRegistrationForm(forms.ModelForm):
    class Meta:
        model = Parent
        fields = '__all__'

class StudentRegistrationForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = '__all__'
        exclude = ['parent']

views.py:

class Registration(MultiModelFormView):
    form_classes = {
        'parent_form' : ParentRegistrationForm,
        'student_form' : StudentRegistrationForm,
    }
    template_name = 'registration/index.html'

    def get_success_url(self):
        return reverse('registration')

    def forms_valid(self, forms):
        parent = forms['parent_form'].save(commit=False)
        student = forms['student_form'].save(commit=False)

        return super(Registration, self).forms_valid(forms)

I am struggling to work out how I can save the parent first and then reference this saved parent for the parent value in my students model form.

CodePudding user response:

forms_valid() calls save() on each form so by overriding you will save the first form or get the values from the first form like getting the photo from the below photo_form and then assign it to the record form then save the record form.

Example:

def forms_valid(self, forms):
    photo = forms['photo_form'].save()
    record = forms['record_form'].save(commit=False)
    record.photo = photo
    record.save()
    return super(RecordFormView, self).forms_valid(forms)

Code Ref

Example on your forms:

def forms_valid(self, forms):
    parent = forms['parent_form'].save()
    student = forms['student_form'].save(commit=False)
    student.parent = parent
    student.save()

    return super(Registration, self).forms_valid(forms)
  • Related