Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a form wizard where, in the first step, an instance of model A is created and then, in the second step, model B is created with a ForeignKey field that should contain the model A instance from step 1. Thus, for validation to work, I need to save the step 1 form (perhaps commit=False in case the user chooses to go back a step?) between steps 1 and 2. What is the best way to do this?

like image 582
Dmitriy Smirnov Avatar asked Dec 05 '25 16:12

Dmitriy Smirnov


1 Answers

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")
like image 152
Vladir Parrado Cruz Avatar answered Dec 08 '25 07:12

Vladir Parrado Cruz



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!