如何根据表单中另一个字段的值隐藏/显示Django酥脆表单中的表单字段。
例如 字段A的下拉菜单中包含选项“ 1”和“ 2” 当字段A ='1'时显示字段B 当字段A ='2'时显示字段C 其他所有字段均以常规方式显示
我在论坛上尝试了多种查询/ javascript解决方案,但它们似乎不适用于松脆的表格。
也许我误解了这些解决方案,否则它们将无法在Crispy表单上使用。
Models.py
class TestCondition(models.Model):
some_name = models.ForeignKey(key_name, on_delete=models.CASCADE)
A_type_choices = (
('1','1'),
('2','2'),
)
Field_A = models.CharField(max_length=20,choices= A_type_choices,default='1')
B_field_choices = (
('abc','ABC'),
('cba','CBA'),
)
Field_B = models.CharField(max_length=20,choices= B_field_choices,default='abc',blank=True,)
Field_C = models.CharField(max_length=40, blank=True, default='')
views.py
class ViewUpdateTestCondition(LoginRequiredMixin,UpdateView):
model = TestCondition
template_name = 'update.html'
form_class = TestConditionForm
class TestConditionForm(ModelForm):
class Meta:
model = TestCondition
fields = ('some_name','Field_A','Field_B','Field_C')
def __init__(self, *args, **kwargs):
super(ModelconfigForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(form=self)
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-8'
self.helper.form_method = 'post' # this line sets your form's method to post
self.helper.layout = Layout(
Fieldset(
'Test Condition',
Field('some_name', type='hidden'),
('Field_A','Field_B','Field_C')),
FormActions(
Submit('submit', "Save changes")
)
)
Update.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script>
function Hide() {
if(document.getElementById('id_Field_A').options[document.getElementById('Field_A').selectedIndex].value == "1") {
document.getElementById('id_Field_B').style.display = 'none';
document.getElementById('id_Field_C').style.display = '';
} else {
document.getElementById('id_Field_B').style.display = '';
document.getElementById('id_Field_C').style.display = 'none';
}
}; </script>
{% load crispy_forms_tags %}
{% crispy form form.helper%}
{% endblock %}
答案 0 :(得分:0)
感谢art06!我添加了以下内容,并且很吸引人。
<script type="text/javascript"> window.addEventListener("load", Hide);</script> <script type="text/javascript"> var el = document.getElementById("div_id_Field_A"); el.addEventListener("click", Hide);</script>