Understanding Baseinlineformset and inlineformset_factory.

278 views
Skip to first unread message

NIKHIL RAJGARHIA

unread,
Aug 4, 2020, 3:02:23 PM8/4/20
to Django users
Hi All,

I am unable to understand the below logic for 'BaseInlineFormSet' and 'inlineformset_factory'.

1. What is the use of 'formset' in 'inlineformset_factory'?
2. What is the use of validation inside 'BaseInlineFormSet'? How it works? I haven't seen any implementation like this validation in normal forms.

As I have only worked with general forms, I was exploring on 'formset', but, couldn't understand this piece of example. I know 'formset' is used to create multiple forms on the same page.

AnswerFormSet = inlineformset_factory( #this will be an instance of the form
        Question,  # parent model
        Answer,  # base model or child model
        formset=BaseAnswerInlineFormSet,
        fields=('text', 'is_correct'),
        min_num=2,
        validate_min=True,
        max_num=10,
        validate_max=True
    )

class BaseAnswerInlineFormSet(forms.BaseInlineFormSet):
    def clean(self):
        super().clean()

        has_one_correct_answer = False
        for form in self.forms:
            if not form.cleaned_data.get('DELETE', False):
                if form.cleaned_data.get('is_correct', False):
                    has_one_correct_answer = True
                    break

        if not has_one_correct_answer:
            raise ValidationError('Mark at least one answer as correct.', code='no_correct_answer')

Thank you in advance.


NIKHIL RAJGARHIA

unread,
Aug 5, 2020, 6:30:52 AM8/5/20
to Django users
Any hint on the above doubt will work fine.
Reply all
Reply to author
Forward
0 new messages