首页 > 解决方案 > UnitTest for Django Inline Formset

问题描述

I have a formset with custom validation logic:

forms.py

class MyFormSet(BaseInlineFormSet):
    def clean(self):
        super().clean()
        forms = list(filter(lambda form: len(form.cleaned_data), self.forms))

        if not forms or any(self.errors):
            return

        for form in forms:
            ...

And I use this custom formset in admin-site models:

admin.py

class MyInline(admin.TabularInline):
    formset = MyFormSet
    model = ClientAgreement

class ClientAdmin(admin.ModelAdmin):
    form = Client
    inlines = [
        MyInline
    ]

So what I want to do now - test my custom clean logic in unit test. Inside the test I create formset with:

formset = inlineformset_factory(Client, ClientAgreement, formset=MyInlineFormSet, fields='all')

After that I create instance with my object:

object_formset = formset(instance=client1)

Now I can see all prepopulated test data inside object_formset according to ClientAdmin model.

But how can I pass changes to forms data to check my clean logic? Or maybe there is different path to solve this?

EDIT

Found out how to pass data into formset:

data = {
            'client_agreements-TOTAL_FORMS': '2',
            'client_agreements-INITIAL_FORMS': '2',
            'client_agreements-1-id': self.second_client_agreement,
            'client_agreements-1-agreement': self.second_client_agreement.agreement,
            'client_agreements-1-is_default': False,
            'client_agreements-0-id': self.online_client_agreement,
            'client_agreements-0-agreement': self.first_client_agreement.agreement,
            'client_agreements-0-is_default': True,
}

client_formset = formset(data, instance=self.second_client)
client_formset.save()

This leads to my goal - clean method in MyFormSet, but after super().clean() passed I receive error for each non-boolean field: 'Select a valid choice. That choice is not one of the available choices.' So I still can't reach my custom logic to test.

标签: pythondjangoformsunit-testinginline-formset

解决方案


推荐阅读