Darkstarone
Darkstarone

Reputation: 4730

Django form validation: get child form data in parent

I'm wondering if there's a way to access Inline forms when validating the parent. For example, if my setup looks like:

admin.py

class ChildInline(nested_admin.NestedTabularInline):
    form = forms.ChildInlineForm
    model = models.Child
    extra = 0


@admin.register(models.Parent)
class ParentAdmin(nested_admin.NestedModelAdmin):
    form = forms.ParentForm
    inlines = [ChildInline]

models.py

class Parent(models.Model):
    name = models.CharField(max_length=10)

class Child(models.Model):
    name = models.CharField(max_length=10)
    parent = models.ForeignKey(
        Parent, on_delete=models.CASCADE, related_name='children'
    )

forms.py

class ChildForm(forms.ModelForm):
    class Meta:
        model = models.Child
        fields = '__all__'


class ParentForm(forms.ModelForm):
    class Meta:
        model = models.Parent
        fields = '__all__'

    def clean(self):
        super().clean()
        # How would I access the ChildForm here?

Is there a way to access the ChildForm from the ParentForm.clean() I realize I could get parent data in the child - but my usecase involves multiple children that have data to pass to the parent - and I'd like to validate at the top level (if possible).

I've also tried doing the validation in the model.Parent.clean() method, but Child models are saved after the parent so this also seems like a non-starter.

Going off the answer below I'ev also tried using a custom formset:

class ParentFormSet(forms.BaseModelFormSet):

    def clean(self):
        if any(self.errors):
            return
        for f in self.forms:
            print(f.cleaned_data)

class ParentForm(forms.ModelForm):
    class Meta:
        model = models.Parent
        fields = '__all__'
    formset = ParentFormSet

But nothing is ever printed so it doesn't seem to be accessed?

Upvotes: 5

Views: 1588

Answers (1)

RHSmith159
RHSmith159

Reputation: 1592

You might be able to override the ModeAdmin method save_formset()? https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_formset


@admin.register(models.Parent)
class ParentAdmin(nested_admin.NestedModelAdmin):
    form = forms.ParentForm
    inlines = [ChildInline]

    def save_formset(self, request, form, formset, change):
        parent_form = form
        for form_set_form in formset:
            if formset_form.is_valid():
                form_set_form_data = form_set_form.cleaned_data
                # do some validation here...
        formset.save()



Upvotes: 1

Related Questions