Tuesday, August 4, 2020

Understanding Baseinlineformset and inlineformset_factory.

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.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/73b5c181-be5b-48c7-a0aa-cb4e1648d80do%40googlegroups.com.

No comments:

Post a Comment