CodexBloom - Programming Q&A Platform

Django 4.0 Form Validation: Custom Validator Not Being Triggered on Nested Fields

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
django forms validation Python

I'm having trouble with a custom validator for nested fields in a Django form. I have a model with a nested structure where a `Profile` model is linked to a `User` model. I want to ensure that the `age` field in the `Profile` model is always greater than 18 when validating the form. However, the custom validator doesn't seem to be triggered when I submit the form, and no validation errors are raised, even when the `age` is set to 15. Here's my setup: ```python # models.py from django.db import models class User(models.Model): username = models.CharField(max_length=150) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.PositiveIntegerField() ``` ```python # forms.py from django import forms from .models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['age'] def clean_age(self): age = self.cleaned_data.get('age') if age < 18: raise forms.ValidationError('Age must be greater than 18.') return age ``` In my view, I am using the form like this: ```python # views.py from django.shortcuts import render, redirect from .forms import ProfileForm def profile_view(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form.save() return redirect('success') else: form = ProfileForm() return render(request, 'profile.html', {'form': form}) ``` When I submit the form with `age=15`, I expect a validation behavior, but it just redirects to the success page without raising any errors. I've confirmed that the form is being initialized properly and that the `clean_age` method should be called. I'm using Django version 4.0. What am I missing here? Is there an scenario with how the form is configured, or with the way I'm handling the POST request? Any insights would be greatly appreciated! I'd really appreciate any guidance on this.