[Django]-Django Form Wizard – Step 2 has ForeignKey field whose instance is created in Step 1 – How to validate?

3👍

I think that you can manage it when you reimplement “done” wizard method, just in the instant when you will save your forms’ data to the database (Depends of your final aim, but if you are usind a wizard likely you are seeking that the data be saved at the end of the wizard). Think about those:

  • If the user has passed the “step 1”, so the data he has put in this step is correct.
  • If the user has passed the “step 2” the data he has put in this step is correct too, and so on. Read the details on the django doc.

Thus, you can make a form for B without be so much worried about “A” data in the “step 2”, cause when you be in the “last step” of the wizard A data will be valid. My thought about is that you can make a B form only with the data you are thinking to save from B but without the reference to A. For example if we have a BModel as follow below:

Class B(models.Model):
    a = models.ForeignKey('A')
    name = models.CharField(max_lenght=50)

you can create a form for B with:

Class BForm(forms.Form):
    name = forms.CharField(max_length=50)

and finally in the “done” method where you have a form_list with all of its forms valid you can do:

def done(self, form_list, **kwargs):
    b_data = {}
    for form in form_list:
        # Getting the A instance
        if isinstance(form, AForm):
            a_instance = form.save()
        # Getting B data
        elif isinstance(form, BForm):
            b_data = form.cleaned_data
        else:
            form.save()
    b_data.update({'a': a_instance})
    BModel.objects.create(**b_data)
    return redirect("success_url")

Leave a comment