4

I have a form, LabelingForm() with two multiplechoicefields and I wish to set the required - parameter so that it is False when pressing button A and B but True when pressing button C. I 've tried with initial = False and required = True but it doesn't work, it requires field choice when pressing button A.

in forms.py

class LabelingForm(forms.Form):



    First_choices = (('1',''),

             .....
            )

    First_choice = forms.MultipleChoiceField(choices=First_choices, initial=True,required=True)


    Second__choices = (('1',''),

      .....
            )

   Second_choice = forms.MultipleChoiceField(choices=Second_choices, initial=True,required=True)

in views.py

def function(request, postID):
       if request.method == 'POST':
          form = LabelingForm(request.POST)
          if form.is_valid():

        if "A" in request.POST:
             # required is false 

        if "B" in request.POST:
             # required is false 

        if "C" in request.POST:
             # required is true
           # change required to True 
            form.fields['First_choice'].required = True
            form.fields['Second_choice'].required = True

in template

<form  action="" method="post">{% csrf_token %}
 <input type="submit"  name="A" value="Submit A"></input>

 <input type="submit"  name="B" value="Submit B"></input>
 # change so that required is True
 {{ labelingform.first_choice}}{{ labelingform.second_choice}}<input type="submit"  name="C" value="Submit C"></input>

</form>
user1749431
  • 559
  • 6
  • 21

1 Answers1

6

Change the required attribute before the calling of is_valid():

   if request.method == 'POST':
      form = LabelingForm(request.POST)

      required = 'C' in request.POST
      form.fields['First_choice'].required = required
      form.fields['Second_choice'].required = required

      if form.is_valid():
          ...
catavaran
  • 44,703
  • 8
  • 98
  • 85
  • Just to mention that in newer versions it should be: form.fields['First_choice'].required = True form.fields['Second_choice'].required = True – Diego Oct 08 '20 at 00:30
  • `if request.method == 'POST':` was the solution for men, I saw other answers for this and they never had `if request.method == 'POST':`, so I thought you didn't need this. – AnonymousUser Apr 15 '22 at 04:42