开发者

Conditionally required fields across forms?

I've got two forms on one page. If a user selects a certain option on one form, I want to make an option on the other form no longer required. How can I do that? I don't think I can put the logic in the clean method because they're开发者_Go百科 separate forms.


You can do this in the view, as long as you set the required flag to False before you call is_valid on your 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 will be valid if other_field_required was False

Or, you could add myform2 as an argument to your first form's __init__ method, then you can put the logic in the 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)
    ...


I would disable the fields using javascript. I would recommend looking up JQuery.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜