python / expert
Snippet
Django Form Array Validation with Granular Error Collection
Validating array-like datasets within Django form fields requires granular error collection. This snippet demonstrates iterating over elements in a list/array, performing validation checks per element, and raising aggregated ValidationErrors.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from django import formsfrom django.core.exceptions import ValidationErrorclass BatchIdListField(forms.CharField):"""Custom form field parsing and validating arrays of integer identifiers."""def clean(self, value):raw_value = super().clean(value)if not raw_value:return []tokens = [token.strip() for token in raw_value.split(",")]validated_ids = []errors = []for index, token in enumerate(tokens):if not token.isdigit():errors.append(ValidationError(f"Item at index {index} ('{token}') is not a valid integer."))else:validated_ids.append(int(token))if errors:raise ValidationError(errors)return validated_ids
django
Breakdown
1
class BatchIdListField(forms.CharField):
Subclasses CharField to transform raw input text into a validated integer list array.
2
tokens = [token.strip() for token in raw_value.split(",")]
Splits comma-separated string into an array of string tokens.
3
for index, token in enumerate(tokens):
Iterates over each element in the array while maintaining index positions for error context.
4
if errors: raise ValidationError(errors)
Raises a list of collected ValidationError instances so Django forms display all invalid element notifications simultaneously.