CodexBloom - Programming Q&A Platform

Django 4.1 Forms: How to Validate Nested Data in a Custom Form Field

πŸ‘€ Views: 1 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
django forms validation Python

Hey everyone, I'm running into an issue that's driving me crazy. I'm working on a Django 4.1 project where I need to create a custom form that takes in nested data. Specifically, I have a form that collects user information, including a list of phone numbers. Each phone number should be validated to ensure it matches a specific format. However, I'm running into issues with validating this nested data when using a custom field. Here’s a simplified version of my form code: ```python from django import forms from django.core.exceptions import ValidationError class PhoneNumberField(forms.Field): def to_python(self, value): if isinstance(value, list): return value raise ValidationError('Input must be a list of phone numbers.') def validate(self, value): super().validate(value) for phone in value: if not isinstance(phone, str) or not phone.isdigit() or len(phone) != 10: raise ValidationError(f'Invalid phone number: {phone}') class UserForm(forms.Form): name = forms.CharField(max_length=100) phone_numbers = PhoneNumberField() ``` When I submit the form with valid phone numbers like `['1234567890', '0987654321']`, it works fine, but if I submit anything else (like `['12345', '123ABC']`), I get a `ValidationError` as expected. The question arises when I try to submit an empty list or `None`. I receive this behavior: `ValueError: too many values to unpack (expected 2)` in the `validate` method of the base `Field` class. I thought about overriding the `clean` method in `UserForm` to handle the empty list case, but I'm not sure how to maintain the logic of the custom phone number validation while also preventing this behavior. What’s the best way to handle this situation? Any help or guidance would be greatly appreciated! For context: I'm using Python on Ubuntu.