Nebulosar
Nebulosar

Reputation: 1855

Raise validation error from child form on parent form in Django

Let's say I have this form:

from django import forms
from django.core.exceptions import ValidationError

class NameForm(forms.form):
    name = forms.CharField(max_length=200)

class NameAgeForm(NameForm):
    age = forms.IntegerField()

    def clean(self):
        data = self.cleaned_data
        if data.get('age') == 24 and data.get('name') == 'Nebu':
            raise ValidationError({'name': "You can't pick that name and age, they are mine!"})

The thing is, I have a sub-form where validation is happening. But I want my field error being shown at the NameForm.

Sidenote I can't access the parent form and therefore the solution must come from the child.

Now, is this possible?

Upvotes: 0

Views: 425

Answers (1)

ramganesh
ramganesh

Reputation: 811

Clean() method on your NameAgeForm It must add custom validation for each field. For field-specific validation, This field validation specific to your current form, We don’t want to put it into the ChildForm. Instead, we write a cleaning method in ParentForm. So Django doesn't help you.

Upvotes: 1

Related Questions