根据视图中的条件(Django)更改窗体中的必填字段 [英] Changing required field in form based on condition in views (Django)
本文介绍了根据视图中的条件(Django)更改窗体中的必填字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
in forms.py
pre>
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 = LabelelingForm(request.POST)
如果form.is_valid():
如果请求中的A.POST:
#必需是false
如果B在request.POST:
#必需是假
如果C在request.POST:
#必需是真的
#需要更改to True
form.fields ['First_choice']。required = True
form.fields ['Second_choice']。required = True
在模板中
< form action =method =post > {%csrf_token%}
< input type =submitname =Avalue =提交A>< / input>
< input type =submitname =Bvalue =提交B>< / input>
#更改,所以必需的是True
{{labelsform.first_choice}} {{labelsform.second_choice}}< input type =submitname =Cvalue =Submit C> < /输入>
< / form>
解决方案
更改 code>属性之前调用
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
如果form.is_valid():
..
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>
解决方案
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():
...
这篇关于根据视图中的条件(Django)更改窗体中的必填字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文