What is the best way to dynamically hide or show a form field in Django crispy forms depending on the selected value of another field in the form?
For example: Field A contains a dropdown menu with options '1' and '2'. Field B should be displayed when Field A is set to '1'. Field C should be displayed when Field A is set to '2'. All other fields should remain visible in their default state.
I have experimented with various query and JavaScript solutions found on forums, but none of them seem to work correctly with crispy forms.
Links to related forum discussions: Link1, Link2, Link3
It is possible that I am misinterpreting the solutions provided or that they are not compatible with Crispy forms.
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'
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 %}