Search code examples
djangodjango-forms

Pass values between Forms


I have several forms(I'm not using formwizard) I want to take decisions based in the value of previous form. For instance: - disable a form2.field the if form1.field has a specific value - Transfer a value from form1 to form2 I'd like to put all the logic in the forms.

I was trying to get the value in the save in the session from the form, I couldn't

class form1(forms.ModelForm):
...

class form2(forms.ModelForm):

    def __init__(self,*args, **kwargs):
       ms = kwargs.pop('fieldform1',None)
       if ms == 'value':
          self.fields['fieldform1'].widget.attrs['readonly'] = True

Solution

  • You can update get_form_kwargs method in your view to pass form1 field values

    def get_form_kwargs(self):
        """Returns the keyword arguments for instantiating the form."""
        kwargs = super(YourViewName, self).get_form_kwargs()
        kwargs['fieldform1'] = 'fieldform1value'
        return kwargs
    

    Ref django views