willer2k
willer2k

Reputation: 546

Django - How to pass a form instance from one view to another

I have a form with multi steps in it. First part uses a forms.ModelForm, once completed, the user is re-directed to another view with a forms.Form in it.

Ideally, I would like to save the first form only if the secondary form is valid and save them both at the same time if that's the case.

I usually use self.request.session to pass data from one view to another, but a form's instance is not serializable, hence, can not append it to the session.

As an example:

FirstView contains FirstForm with fields ('firstname', 'lastname')

SecondView contains SecondForm with fields ('address', 'gender')

If FirstForm and SecondForm is valid
  form1.save
  form2.save

Would anyone have any suggestions? Thank you.

Upvotes: 3

Views: 1830

Answers (1)

ruddra
ruddra

Reputation: 52028

Well, you can store form's cleaned_data in django session and pass it to another form as initial. For example:

def first_view(request):
   form = FirstForm(request.POST)
   if form.is_valid():
       request.session['first_form'] = form.cleaned_data
       return redirect('to_second_view')

def second_view(request):
     form = SecondForm(request.POST)
     if form.is_valid():
        first_form_data = request.session.pop('first_form',{})
        first_form_instance = FirstFormModel.objects.create(**first_form_data)
        second_form_instance = form.save()
     # rest of the code...

Upvotes: 4

Related Questions