django - Conditionally required fields across forms? -
i've got 2 forms on 1 page. if user selects option on 1 form, want make option on other form no longer required. how can that? don't think can put logic in clean
method because they're separate forms.
you can in view, long set required flag false before call is_valid on second form.
class myform1(forms.form): other_field_required = forms.booleanfield(required=false) class myform2(forms.form): sometimes_required = forms.charfield(required=true) def myview(request): form1 = myform1(request.post) form2 = myform2(request.post) if form1.is_valid(): if not form1.cleaned_data['other_field_required']: form2.fields['sometimes_required'].required = false ... if form2.is_valid(): # form2 valid if other_field_required false
or, add myform2
argument first form's __init__
method, can put logic in clean
method.
class myform1(forms.form): other_field_required = forms.booleanfield(required=false) def __init__(myform2, *args, **kwargs): super(myform1, self).__init__(*args, **kwargs) self.form2 = form2 def clean(self): if not self.cleaned_data['other_field_required']: self.form2.fields['other_field_required'].required = false ... def myview(request): form2 = myform2(request.post) form1 = myform1(form2, data=request.post) ...
Comments
Post a Comment