Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 724
Darkstarone Avatar asked Nov 16 '22 18:11

Darkstarone


1 Answers

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()



like image 151
RHSmith159 Avatar answered Mar 31 '23 22:03

RHSmith159