【问题标题】:dynamic form in django using choiceFielddjango中使用choiceField的动态表单
【发布时间】:2021-10-15 01:47:24
【问题描述】:

我正在使用 django 构建我的第一个网络应用程序,并且很难弄清楚如何使用动态表单来为不同的选择提供不同的输出。

例如,对于我的度量选择定性,我希望表单相同(没有额外的字段),但如果选择定量值,我希望我的模板再显示两个字段(value_min 和 value_max)

the first option when qualitative value is selected

the second option when quantitative value is selected

感谢您的帮助...

【问题讨论】:

    标签: javascript django


    【解决方案1】:

    您不能将django tags 用于条件,因为它只从后端呈现,所以这是一个前端问题。在我的实现中,我通常使用带有以下想法的 javascript:

    • 从不显示最小值和最大值开始 (style.display = "None")
    • 将EventListener(onChange 类型)添加到选择器(在您的情况下为 Mesure)
    • 用javascript检查是否满足条件,将style.display改为block,例如

    【讨论】:

      【解决方案2】:

      在页面加载之前在模板上呈现表单。因此,django 变量不能被用户操作。

      在渲染表单时,django 允许您为表单字段设置类。使用它们来隐藏额外的字段。

      示例value_min = forms.CharField(widget=forms.TextInput(attrs={'class':'hide'}))

      您可以在clean 时添加表单检查

       class MYform(forms.Form):
           #....
           def clean_min_value(self):
             #check here for choice field value
             #return value or blank accordingly
      

      同样,您可以将验证器添加到表单中,以确保仅在选择为quantitative

      时将其设置为此值。

      value_min = forms.CharField(widget=forms.TextInput(attrs={'class':'hide'}), validators=[check_choice])

       def check_choice(Value):
         # validate Value
      

      【讨论】:

        【解决方案3】:

        感谢@videap 和@Rhea 的帮助...所以我想出了如何使用videap 的指导和帖子Show and hide dynamically fields in Django form 来解决我的问题

        所以解决办法是:

        表格:

        class NewCriterioForm(forms.ModelForm):
            parent = TreeNodeChoiceField(queryset=Criteria.objects.all())
            def __init__(self,*args,**kwargs):
                super().__init__(*args,**kwargs)
                
                self.criteria_CHOICES = [('FunCriteria','FunCriteria'),('nonFunCriteria','nonFunCriteria')]
                self.mesure_CHOICES = (('Quantitative','Quantitative'),('Qualitative','Qualitative'))
                self.fields['parent'].label=''
                self.fields['parent'].required=False
                self.fields['type']= forms.CharField(widget=forms.Select(choices=self.criteria_CHOICES))
                self.fields['mesure']= forms.ChoiceField(choices=self.mesure_CHOICES)
            class Meta:
                model = Criteria
                fields = ('name', 'parent', 'type','slug','description','mesure','value_min','value_max')
        
                }
        

        对于视图:

        ......
        criterion = NewCriterioForm()
            return render(request, 'addCriteria.html', {'criterion': criterion})
        

        最后,在模板中,我输入了这段代码:

                      <script>
                        function Hide() {
                            if(document.getElementById('id_mesure').options[document.getElementById('id_mesure').selectedIndex].value == "Qualitative") {
                                 document.getElementById('id_value_min').style.display = 'none';
                                 document.getElementById('id_value_max').style.display = 'none';
                            } else {
                                 document.getElementById('id_value_min').style.display = '';
                                 document.getElementById('id_value_max').style.display = '';
                            }
                        }
                        
                        window.onload = function() {
                            document.getElementById('id_mesure').onchange = Hide;
                        };
                        </script>
                       
                        <div>
                            {{ criterion.name.label_tag }}{{ criterion.name }}
                        </div>
                        <tr></tr>
                        <div>
                            {{ criterion.parent.label_tag }}{{ criterion.parent }}
                        </div>
                        <div>
                            {{ criterion.type.label_tag }}{{ criterion.type }}
                        </div>
        
                        <div>
                          {{ criterion.slug.label_tag }}{{ criterion.slug }}
                         </div>
                         <div>
                          {{ criterion.description.label_tag }}{{ criterion.description }}
                          </div>
                          <div>
                          {{ criterion.mesure.label_tag }}{{ criterion.mesure }}
                          </div>
        
                        <div id="id_value_min">
                        {{ criterion.value_min.label_tag }}{{ criterion.value_min }}
                        </div>
                          <div id="id_value_max">
                            {{ criterion.value_max.label_tag }}{{ criterion.value_max }}
                         </div>
        
        

        【讨论】:

          猜你喜欢
          • 2014-08-22
          • 1970-01-01
          • 1970-01-01
          • 2014-07-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-30
          • 2012-09-18
          相关资源
          最近更新 更多