Here's a comprehensive approach for creating a generic method to handle conditional field visibility and validation in Django forms:
1. Base Form Class with Conditional Logic
class ConditionalForm(forms.Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.conditional_rules = self.get_conditional_rules()
self.apply_conditional_logic()
def get_conditional_rules(self):
"""
Override this method to define conditional rules.
Return a list of dictionaries with the following structure:
{
'trigger_field': 'field_name',
'trigger_value': 'value_to_match',
'target_fields': ['field1', 'field2'],
'action': 'show' # or 'hide'
}
"""
return []
def apply_conditional_logic(self):
"""Apply conditional logic to form fields"""
for rule in self.conditional_rules:
trigger_field = rule['trigger_field']
trigger_value = rule['trigger_value']
target_fields = rule['target_fields']
action = rule.get('action', 'show')
# Get current value of trigger field
current_value = self.data.get(trigger_field) if self.is_bound else self.initial.get(trigger_field)
# Determine if condition is met
condition_met = self._evaluate_condition(current_value, trigger_value)
# Apply action to target fields
for field_name in target_fields:
if field_name in self.fields:
if action == 'show' and condition_met:
self._show_field(field_name)
elif action == 'hide' and condition_met:
self._hide_field(field_name)
elif action == 'show' and not condition_met:
self._hide_field(field_name)
elif action == 'hide' and not condition_met:
self._show_field(field_name)
def _evaluate_condition(self, current_value, trigger_value):
"""Evaluate if condition is met - can be extended for complex conditions"""
if callable(trigger_value):
return trigger_value(current_value)
return str(current_value) == str(trigger_value)
def _hide_field(self, field_name):
"""Hide a field by adding CSS class and making it not required"""
field = self.fields[field_name]
field.widget.attrs.update({'class': field.widget.attrs.get('class', '') + ' conditional-hidden'})
field.widget.attrs.update({'style': 'display: none;'})
# Store original required state
if not hasattr(field, '_original_required'):
field._original_required = field.required
field.required = False
def _show_field(self, field_name):
"""Show a field by removing hidden styles and restoring required state"""
field = self.fields[field_name]
# Remove hidden class and style
css_class = field.widget.attrs.get('class', '').replace('conditional-hidden', '').strip()
field.widget.attrs.update({'class': css_class})
if 'style' in field.widget.attrs:
del field.widget.attrs['style']
# Restore original required state
if hasattr(field, '_original_required'):
field.required = field._original_required
def clean(self):
cleaned_data = super().clean()
# Validate conditional fields
for rule in self.conditional_rules:
trigger_field = rule['trigger_field']
trigger_value = rule['trigger_value']
target_fields = rule['target_fields']
action = rule.get('action', 'show')
required_when_visible = rule.get('required_when_visible', True)
trigger_field_value = cleaned_data.get(trigger_field)
condition_met = self._evaluate_condition(trigger_field_value, trigger_value)
# Determine if fields should be visible
fields_should_be_visible = (action == 'show' and condition_met) or (action == 'hide' and not condition_met)
for field_name in target_fields:
field_value = cleaned_data.get(field_name)
if fields_should_be_visible and required_when_visible and not field_value:
self.add_error(field_name, f"This field is required when {trigger_field} is {trigger_field_value}")
elif not fields_should_be_visible and field_value:
# Clear the value if field shouldn't be visible
cleaned_data[field_name] = None
return cleaned_data
2. Example Usage
class UserRegistrationForm(ConditionalForm):
user_type = forms.ChoiceField(choices=[
('individual', 'Individual'),
('company', 'Company'),
])
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
company_name = forms.CharField(max_length=200, required=False)
tax_id = forms.CharField(max_length=50, required=False)
has_experience = forms.BooleanField(required=False)
years_experience = forms.IntegerField(required=False)
previous_company = forms.CharField(max_length=200, required=False)
def get_conditional_rules(self):
return [
{
'trigger_field': 'user_type',
'trigger_value': 'company',
'target_fields': ['company_name', 'tax_id'],
'action': 'show',
'required_when_visible': True
},
{
'trigger_field': 'has_experience',
'trigger_value': True,
'target_fields': ['years_experience', 'previous_company'],
'action': 'show',
'required_when_visible': True
}
]
3. JavaScript for Dynamic Frontend Behavior
// Add this to your template
document.addEventListener('DOMContentLoaded', function() {
function setupConditionalFields() {
// Get all form fields that might trigger conditional logic
const triggerFields = document.querySelectorAll('[data-conditional-trigger]');
triggerFields.forEach(field => {
field.addEventListener('change', function() {
updateConditionalFields();
});
});
// Initial setup
updateConditionalFields();
}
function updateConditionalFields() {
// This would need to be customized based on your specific rules
// or you could pass the rules from Django to JavaScript
const conditionalRules = JSON.parse(document.getElementById('conditional-rules').textContent);
conditionalRules.forEach(rule => {
const triggerField = document.querySelector(`[name="${rule.trigger_field}"]`);
const triggerValue = triggerField.value;
rule.target_fields.forEach(fieldName => {
const targetField = document.querySelector(`[name="${fieldName}"]`);
const fieldContainer = targetField.closest('.form-group') || targetField.parentElement;
const conditionMet = evaluateCondition(triggerValue, rule.trigger_value);
const shouldShow = (rule.action === 'show' && conditionMet) ||
(rule.action === 'hide' && !conditionMet);
if (shouldShow) {
fieldContainer.style.display = '';
if (rule.required_when_visible) {
targetField.required = true;
}
} else {
fieldContainer.style.display = 'none';
targetField.required = false;
targetField.value = ''; // Clear hidden field values
}
});
});
}
function evaluateCondition(currentValue, triggerValue) {
return String(currentValue) === String(triggerValue);
}
setupConditionalFields();
});
4. Template Integration
<!-- In your template -->
{{ conditional_rules|json_script:"conditional-rules" }}
<form method="post">
{% csrf_token %}
<div class="form-group">
{{ form.user_type.label_tag }}
{{ form.user_type }}
{{ form.user_type.errors }}
</div>
<div class="form-group">
{{ form.first_name.label_tag }}
{{ form.first_name }}
{{ form.first_name.errors }}
</div>
<!-- Add data attribute to trigger fields -->
<script>
document.querySelector('[name="user_type"]').setAttribute('data-conditional-trigger', 'true');
document.querySelector('[name="has_experience"]').setAttribute('data-conditional-trigger', 'true');
</script>
<!-- Rest of your form fields -->
<button type="submit">Submit</button>
</form>
5. Advanced Features
For more complex scenarios, you can extend the base class:
class AdvancedConditionalForm(ConditionalForm):
def get_conditional_rules(self):
return [
{
'trigger_field': 'age',
'trigger_value': lambda x: int(x or 0) >= 18, # Custom condition
'target_fields': ['can_vote'],
'action': 'show'
},
{
'trigger_field': 'multiple_fields',
'trigger_value': lambda form_data: (
form_data.get('field1') == 'value1' and
form_data.get('field2') == 'value2'
), # Multiple field condition
'target_fields': ['conditional_field'],
'action': 'show'
}
]
This approach provides a clean, reusable way to handle conditional form fields with both frontend interactivity and backend validation. The rules are defined declaratively, making them easy to understand and maintain.