我有一个表单,LabelingForm() 有两个多项选择字段,我希望设置所需的 - 参数,以便在按下按钮 A 和 B 时为 False,但在按下按钮 C 时为 True。我尝试使用 initial = False 和 required = True但它不起作用,按下按钮A时需要选择字段。
在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)
在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
在模板中
<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>