Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 814
willer2k Avatar asked Jan 27 '26 22:01

willer2k


1 Answers

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...
like image 110
ruddra Avatar answered Jan 29 '26 11:01

ruddra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!