django.forms.models.inlineformset_factory - python examples

Here are the examples of the python api django.forms.models.inlineformset_factory taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

40 Examples 7

3 View Complete Implementation : formsets.py
Copyright GNU Affero General Public License v3.0
Author : auvipy
    def formset_factory(self):
        """
        Returns the keyword arguments for calling the formset factory
        """
        kwargs = {
            'formset': self.formset_clast,
            'extra': self.extra,
            'max_num': self.max_num,
            'can_order': self.can_order,
            'can_delete': self.can_delete,
            'fields': self.fields,
            'exclude': self.exclude,
            'formfield_callback': self.formfield_callback,
            'fk_name': self.fk_name
        }
        if self.form_clast:
            kwargs['form'] = self.form_clast
        return inlineformset_factory(self.model, self.inline_model, **kwargs)

3 View Complete Implementation : test_product_forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dinoperovic
    def setUp(self):
        self.formset_factory = inlineformset_factory(
            Product,
            AttributeValue,
            formset=AttributeValueInlineFormSet,
            exclude=[],
        )

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : harikvpy
    def get_formset_clast(self):
        """
        Returns the inline formset clast for adding Books to this author.
        """
        return forms.models.inlineformset_factory(
            Author,
            Book,
            form=CustomBookForm,
            fields=('satle', 'isbn'),
            can_delete=True,
            extra=2)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_deletion(self):
        PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True, fields="__all__")
        poet = Poet.objects.create(name='test')
        poem = poet.poem_set.create(name='test poem')
        data = {
            'poem_set-TOTAL_FORMS': '1',
            'poem_set-INITIAL_FORMS': '1',
            'poem_set-MAX_NUM_FORMS': '0',
            'poem_set-0-id': str(poem.pk),
            'poem_set-0-poet': str(poet.pk),
            'poem_set-0-name': 'test',
            'poem_set-0-DELETE': 'on',
        }
        formset = PoemFormSet(data, instance=poet)
        formset.save()
        self.astertTrue(formset.is_valid())
        self.astertEqual(Poem.objects.count(), 0)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inline_formset_factory(self):
        """
        These should both work without a problem.
        """
        inlineformset_factory(Parent, Child, fk_name='mother', fields="__all__")
        inlineformset_factory(Parent, Child, fk_name='father', fields="__all__")

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_exception_on_unspecified_foreign_key(self):
        """
        Child has two ForeignKeys to Parent, so if we don't specify which one
        to use for the inline formset, we should get an exception.
        """
        msg = "'inline_formsets.Child' has more than one ForeignKey to 'inline_formsets.Parent'."
        with self.astertRaisesMessage(ValueError, msg):
            inlineformset_factory(Parent, Child)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_fk_name_not_foreign_key_field_from_child(self):
        """
        If we specify fk_name, but it isn't a ForeignKey from the child model
        to the parent model, we should get an exception.
        """
        msg = "fk_name 'school' is not a ForeignKey to 'inline_formsets.Parent'."
        with self.astertRaisesMessage(ValueError, msg):
            inlineformset_factory(Parent, Child, fk_name='school')

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_non_foreign_key_field(self):
        """
        If the field specified in fk_name is not a ForeignKey, we should get an
        exception.
        """
        with self.astertRaisesMessage(ValueError, "'inline_formsets.Child' has no field named 'test'."):
            inlineformset_factory(Parent, Child, fk_name='test')

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_any_iterable_allowed_as_argument_to_exclude(self):
        # Regression test for #9171.
        inlineformset_factory(
            Parent, Child, exclude=['school'], fk_name='mother'
        )

        inlineformset_factory(
            Parent, Child, exclude=('school',), fk_name='mother'
        )

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature('allows_auto_pk_0')
    def test_zero_primary_key(self):
        # Regression test for #21472
        poet = Poet.objects.create(id=0, name='test')
        poet.poem_set.create(name='test poem')
        PoemFormSet = inlineformset_factory(Poet, Poem, fields="__all__", extra=0)
        formset = PoemFormSet(None, instance=poet)
        self.astertEqual(len(formset.forms), 1)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_unsaved_fk_validate_unique(self):
        poet = Poet(name='unsaved')
        PoemFormSet = inlineformset_factory(Poet, Poem, fields=['name'])
        data = {
            'poem_set-TOTAL_FORMS': '2',
            'poem_set-INITIAL_FORMS': '0',
            'poem_set-MAX_NUM_FORMS': '2',
            'poem_set-0-name': 'Poem',
            'poem_set-1-name': 'Poem',
        }
        formset = PoemFormSet(data, instance=poet)
        self.astertFalse(formset.is_valid())
        self.astertEqual(formset.non_form_errors(), ['Please correct the duplicate data for name.'])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_fk_not_duplicated_in_form_fields(self):
        """
        A foreign key name isn't duplicated in form._meta fields (#21332).
        """
        poet = Poet.objects.create(name='test')
        poet.poem_set.create(name='first test poem')
        poet.poem_set.create(name='second test poem')
        poet.poem_set.create(name='third test poem')
        PoemFormSet = inlineformset_factory(Poet, Poem, fields=('name',), extra=0)
        formset = PoemFormSet(None, instance=poet)
        self.astertEqual(len(formset.forms), 3)
        self.astertEqual(['name', 'poet'], PoemFormSet.form._meta.fields)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_fk_in_all_formset_forms(self):
        """
        A foreign key field is in Meta for all forms in the formset (#26538).
        """
        clast PoemModelForm(ModelForm):
            def __init__(self, *args, **kwargs):
                astert 'poet' in self._meta.fields
                super().__init__(*args, **kwargs)

        poet = Poet.objects.create(name='test')
        poet.poem_set.create(name='first test poem')
        poet.poem_set.create(name='second test poem')
        PoemFormSet = inlineformset_factory(Poet, Poem, form=PoemModelForm, fields=('name',), extra=0)
        formset = PoemFormSet(None, instance=poet)
        formset.forms  # Trigger form instantiation to run the astert above.

3 View Complete Implementation : test_uuid.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inlineformset_factory_nulls_default_pks(self):
        """
        #24377 - If we're adding a new object, a parent's auto-generated pk
        from the model field default should be ignored as it's regenerated on
        the save request.

        Tests the case where both the parent and child have a UUID primary key.
        """
        FormSet = inlineformset_factory(UUIDPKParent, UUIDPKChild, fields='__all__')
        formset = FormSet()
        self.astertIsNone(formset.forms[0].fields['parent'].initial)

3 View Complete Implementation : test_uuid.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inlineformset_factory_ignores_default_pks_on_submit(self):
        """
        #24377 - Inlines with a model field default should ignore that default
        value to avoid triggering validation on empty forms.
        """
        FormSet = inlineformset_factory(UUIDPKParent, UUIDPKChild, fields='__all__')
        formset = FormSet({
            'uuidpkchild_set-TOTAL_FORMS': 3,
            'uuidpkchild_set-INITIAL_FORMS': 0,
            'uuidpkchild_set-MAX_NUM_FORMS': '',
            'uuidpkchild_set-0-name': 'Foo',
            'uuidpkchild_set-1-name': '',
            'uuidpkchild_set-2-name': '',
        })
        self.astertTrue(formset.is_valid())

3 View Complete Implementation : test_uuid.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inlineformset_factory_nulls_default_pks_uuid_parent_auto_child(self):
        """
        #24958 - Variant of test_inlineformset_factory_nulls_default_pks for
        the case of a parent object with a UUID primary key and a child object
        with an AutoField primary key.
        """
        FormSet = inlineformset_factory(UUIDPKParent, AutoPKChildOfUUIDPKParent, fields='__all__')
        formset = FormSet()
        self.astertIsNone(formset.forms[0].fields['parent'].initial)

3 View Complete Implementation : test_uuid.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inlineformset_factory_nulls_default_pks_auto_parent_uuid_child(self):
        """
        #24958 - Variant of test_inlineformset_factory_nulls_default_pks for
        the case of a parent object with an AutoField primary key and a child
        object with a UUID primary key.
        """
        FormSet = inlineformset_factory(AutoPKParent, UUIDPKChildOfAutoPKParent, fields='__all__')
        formset = FormSet()
        self.astertIsNone(formset.forms[0].fields['parent'].initial)

3 View Complete Implementation : test_uuid.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inlineformset_factory_nulls_default_pks_child_editable_pk(self):
        """
        #24958 - Variant of test_inlineformset_factory_nulls_default_pks for
        the case of a parent object with a UUID primary key and a child
        object with an editable natural key for a primary key.
        """
        FormSet = inlineformset_factory(UUIDPKParent, ChildWithEditablePK, fields='__all__')
        formset = FormSet()
        self.astertIsNone(formset.forms[0].fields['parent'].initial)

3 View Complete Implementation : test_uuid.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inlineformset_factory_nulls_default_pks_alternate_key_relation(self):
        """
        #24958 - Variant of test_inlineformset_factory_nulls_default_pks for
        the case of a parent object with a UUID alternate key and a child
        object that relates to that alternate key.
        """
        FormSet = inlineformset_factory(ParentWithUUIDAlternateKey, ChildRelatedViaAK, fields='__all__')
        formset = FormSet()
        self.astertIsNone(formset.forms[0].fields['parent'].initial)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inline_model_with_to_field(self):
        """
        #13794 --- An inline model with a to_field of a formset with instance
        has working relations.
        """
        FormSet = inlineformset_factory(User, UserSite, exclude=('is_superuser',))

        user = User.objects.create(username="guido", serial=1337)
        UserSite.objects.create(user=user, data=10)
        formset = FormSet(instance=user)

        # Testing the inline model's relation
        self.astertEqual(formset[0].instance.user_id, "guido")

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inline_model_with_to_field_to_rel(self):
        """
        #13794 --- An inline model with a to_field to a related field of a
        formset with instance has working relations.
        """
        FormSet = inlineformset_factory(UserProfile, ProfileNetwork, exclude=[])

        user = User.objects.create(username="guido", serial=1337, pk=1)
        self.astertEqual(user.pk, 1)
        profile = UserProfile.objects.create(user=user, about="about", pk=2)
        self.astertEqual(profile.pk, 2)
        ProfileNetwork.objects.create(profile=profile, network=10, identifier=10)
        formset = FormSet(instance=profile)

        # Testing the inline model's relation
        self.astertEqual(formset[0].instance.profile_id, 1)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_formset_with_none_instance(self):
        "A formset with instance=None can be created. Regression for #11872"
        Form = modelform_factory(User, fields="__all__")
        FormSet = inlineformset_factory(User, UserSite, fields="__all__")

        # Instantiate the Form and FormSet to prove
        # you can create a formset with an instance of None
        Form(instance=None)
        FormSet(instance=None)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_initial_data(self):
        user = User.objects.create(username="bibi", serial=1)
        UserSite.objects.create(user=user, data=7)
        FormSet = inlineformset_factory(User, UserSite, extra=2, fields="__all__")

        formset = FormSet(instance=user, initial=[{'data': 41}, {'data': 42}])
        self.astertEqual(formset.forms[0].initial['data'], 7)
        self.astertEqual(formset.extra_forms[0].initial['data'], 41)
        self.astertIn('value="42"', formset.extra_forms[1].as_p())

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inlineformset_factory_default(self):
        Formset = inlineformset_factory(User, UserSite, form=UserSiteForm, fields="__all__")
        form = Formset().forms[0]
        self.astertIsInstance(form['id'].field.widget, CustomWidget)
        self.astertIsInstance(form['data'].field.widget, CustomWidget)
        self.astertFalse(form.fields['id'].localize)
        self.astertTrue(form.fields['data'].localize)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inline_model_with_primary_to_field(self):
        """An inline model with a OneToOneField with to_field & primary key."""
        FormSet = inlineformset_factory(User, UserPreferences, exclude=('is_superuser',))
        user = User.objects.create(username='guido', serial=1337)
        UserPreferences.objects.create(user=user, favorite_number=10)
        formset = FormSet(instance=user)
        self.astertEqual(formset[0].fields['user'].initial, 'guido')

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : studybuffalo
    def post(self, request, *args, **kwargs):
        """Overriding post method to handle inline formsets."""
        # Setup the formset for PlanCost
        PlanCostFormSet = inlineformset_factory( # pylint: disable=invalid-name
            parent_model=models.SubscriptionPlan,
            model=models.PlanCost,
            form=forms.PlanCostForm,
            can_delete=False,
            extra=1,
        )

        self.object = None
        form = self.get_form(self.get_form_clast())
        cost_forms = PlanCostFormSet(self.request.POST)

        if form.is_valid() and cost_forms.is_valid():
            return self.form_valid(form, cost_forms)
        else:
            return self.form_invalid(form, cost_forms)

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : studybuffalo
    def post(self, request, *args, **kwargs):
        """Overriding post method to handle inline formsets."""
        # Setup the formset for PlanCost
        PlanCostFormSet = inlineformset_factory( # pylint: disable=invalid-name
            parent_model=models.SubscriptionPlan,
            model=models.PlanCost,
            form=forms.PlanCostForm,
            can_delete=True,
            extra=1,
        )

        self.object = self.get_object()
        form = self.get_form(self.get_form_clast())
        cost_forms = PlanCostFormSet(self.request.POST, instance=self.object)

        if form.is_valid() and cost_forms.is_valid():
            return self.form_valid(form, cost_forms)
        else:
            return self.form_invalid(form, cost_forms)

0 View Complete Implementation : inline.py
Copyright Apache License 2.0
Author : BeanWei
    @filter_hook
    def get_formset(self, **kwargs):
        """Returns a BaseInlineFormSet clast for use in admin add/change views."""
        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)
        exclude.extend(self.get_readonly_fields())
        if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
            # Take the custom ModelForm's Meta.exclude into account only if the
            # InlineModelAdmin doesn't define its own.
            exclude.extend(self.form._meta.exclude)
        # if exclude is an empty list we use None, since that's the actual
        # default
        exclude = exclude or None
        can_delete = self.can_delete and self.has_delete_permission()
        defaults = {
            "form": self.form,
            "formset": self.formset,
            "fk_name": self.fk_name,
            'fields': forms.ALL_FIELDS,
            "exclude": exclude,
            "formfield_callback": self.formfield_for_dbfield,
            "extra": self.extra,
            "max_num": self.max_num,
            "can_delete": can_delete,
        }
        defaults.update(kwargs)

        return inlineformset_factory(self.parent_model, self.model, **defaults)

0 View Complete Implementation : test_product_forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dinoperovic
    def test_clean(self):
        formset_factory = inlineformset_factory(
            Attribute,
            AttributeChoice,
            formset=AttributeChoiceInlineFormSet,
            exclude=[],
        )
        formset = formset_factory()

        clast DummyForm(forms.ModelForm):
            clast Meta:
                model = AttributeChoice
                exclude = []

            def __init__(self, *args, **kwargs):
                self.cleaned_data = kwargs.pop('cleaned_data')
                self.cleaned_data['DELETE'] = False
                super(DummyForm, self).__init__(*args, **kwargs)

        form1 = DummyForm(cleaned_data={'value': 1})
        form2 = DummyForm(cleaned_data={'value': 1})  # duplicate
        formset.forms = []
        self.astertRaises(ValidationError, formset.clean)  # no forms
        formset.forms = [form1, form2]
        self.astertRaises(ValidationError, formset.clean)  # duplicate values
        formset.forms = [form1]
        self.astertIsNone(formset.clean())  # past through
        formset.instance = None
        self.astertIsNone(formset.clean())  # no instance

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_add_form_deletion_when_invalid(self):
        """
        Make sure that an add form that is filled out, but marked for deletion
        doesn't cause validation errors.
        """
        PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True, fields="__all__")
        poet = Poet.objects.create(name='test')
        data = {
            'poem_set-TOTAL_FORMS': '1',
            'poem_set-INITIAL_FORMS': '0',
            'poem_set-MAX_NUM_FORMS': '0',
            'poem_set-0-id': '',
            'poem_set-0-poem': '1',
            'poem_set-0-name': 'x' * 1000,
        }
        formset = PoemFormSet(data, instance=poet)
        # Make sure this form doesn't past validation.
        self.astertIs(formset.is_valid(), False)
        self.astertEqual(Poem.objects.count(), 0)

        # Then make sure that it *does* past validation and delete the object,
        # even though the data isn't actually valid.
        data['poem_set-0-DELETE'] = 'on'
        formset = PoemFormSet(data, instance=poet)
        self.astertIs(formset.is_valid(), True)
        formset.save()
        self.astertEqual(Poem.objects.count(), 0)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_change_form_deletion_when_invalid(self):
        """
        Make sure that a change form that is filled out, but marked for deletion
        doesn't cause validation errors.
        """
        PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True, fields="__all__")
        poet = Poet.objects.create(name='test')
        poem = poet.poem_set.create(name='test poem')
        data = {
            'poem_set-TOTAL_FORMS': '1',
            'poem_set-INITIAL_FORMS': '1',
            'poem_set-MAX_NUM_FORMS': '0',
            'poem_set-0-id': str(poem.id),
            'poem_set-0-poem': str(poem.id),
            'poem_set-0-name': 'x' * 1000,
        }
        formset = PoemFormSet(data, instance=poet)
        # Make sure this form doesn't past validation.
        self.astertIs(formset.is_valid(), False)
        self.astertEqual(Poem.objects.count(), 1)

        # Then make sure that it *does* past validation and delete the object,
        # even though the data isn't actually valid.
        data['poem_set-0-DELETE'] = 'on'
        formset = PoemFormSet(data, instance=poet)
        self.astertIs(formset.is_valid(), True)
        formset.save()
        self.astertEqual(Poem.objects.count(), 0)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_save_new(self):
        """
        Make sure inlineformsets respect commit=False
        regression for #10750
        """
        # exclude some required field from the forms
        ChildFormSet = inlineformset_factory(School, Child, exclude=['father', 'mother'])
        school = School.objects.create(name='test')
        mother = Parent.objects.create(name='mother')
        father = Parent.objects.create(name='father')
        data = {
            'child_set-TOTAL_FORMS': '1',
            'child_set-INITIAL_FORMS': '0',
            'child_set-MAX_NUM_FORMS': '0',
            'child_set-0-name': 'child',
        }
        formset = ChildFormSet(data, instance=school)
        self.astertIs(formset.is_valid(), True)
        objects = formset.save(commit=False)
        for obj in objects:
            obj.mother = mother
            obj.father = father
            obj.save()
        self.astertEqual(school.child_set.count(), 1)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_formset_over_to_field(self):
        "A formset over a ForeignKey with a to_field can be saved. Regression for #10243"
        Form = modelform_factory(User, fields="__all__")
        FormSet = inlineformset_factory(User, UserSite, fields="__all__")

        # Instantiate the Form and FormSet to prove
        # you can create a form with no data
        form = Form()
        form_set = FormSet(instance=User())

        # Now create a new User and UserSite instance
        data = {
            'serial': '1',
            'username': 'apollo13',
            'usersite_set-TOTAL_FORMS': '1',
            'usersite_set-INITIAL_FORMS': '0',
            'usersite_set-MAX_NUM_FORMS': '0',
            'usersite_set-0-data': '10',
            'usersite_set-0-user': 'apollo13'
        }
        user = User()
        form = Form(data)
        if form.is_valid():
            user = form.save()
        else:
            self.fail('Errors found on form:%s' % form_set)

        form_set = FormSet(data, instance=user)
        if form_set.is_valid():
            form_set.save()
            usersite = UserSite.objects.all().values()
            self.astertEqual(usersite[0]['data'], 10)
            self.astertEqual(usersite[0]['user_id'], 'apollo13')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

        # Now update the UserSite instance
        data = {
            'usersite_set-TOTAL_FORMS': '1',
            'usersite_set-INITIAL_FORMS': '1',
            'usersite_set-MAX_NUM_FORMS': '0',
            'usersite_set-0-id': str(usersite[0]['id']),
            'usersite_set-0-data': '11',
            'usersite_set-0-user': 'apollo13'
        }
        form_set = FormSet(data, instance=user)
        if form_set.is_valid():
            form_set.save()
            usersite = UserSite.objects.all().values()
            self.astertEqual(usersite[0]['data'], 11)
            self.astertEqual(usersite[0]['user_id'], 'apollo13')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

        # Now add a new UserSite instance
        data = {
            'usersite_set-TOTAL_FORMS': '2',
            'usersite_set-INITIAL_FORMS': '1',
            'usersite_set-MAX_NUM_FORMS': '0',
            'usersite_set-0-id': str(usersite[0]['id']),
            'usersite_set-0-data': '11',
            'usersite_set-0-user': 'apollo13',
            'usersite_set-1-data': '42',
            'usersite_set-1-user': 'apollo13'
        }
        form_set = FormSet(data, instance=user)
        if form_set.is_valid():
            form_set.save()
            usersite = UserSite.objects.all().values().order_by('data')
            self.astertEqual(usersite[0]['data'], 11)
            self.astertEqual(usersite[0]['user_id'], 'apollo13')
            self.astertEqual(usersite[1]['data'], 42)
            self.astertEqual(usersite[1]['user_id'], 'apollo13')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_formset_over_inherited_model(self):
        "A formset over a ForeignKey with a to_field can be saved. Regression for #11120"
        Form = modelform_factory(Restaurant, fields="__all__")
        FormSet = inlineformset_factory(Restaurant, Manager, fields="__all__")

        # Instantiate the Form and FormSet to prove
        # you can create a form with no data
        form = Form()
        form_set = FormSet(instance=Restaurant())

        # Now create a new Restaurant and Manager instance
        data = {
            'name': "Guido's House of Pasta",
            'manager_set-TOTAL_FORMS': '1',
            'manager_set-INITIAL_FORMS': '0',
            'manager_set-MAX_NUM_FORMS': '0',
            'manager_set-0-name': 'Guido Van Rossum'
        }
        restaurant = User()
        form = Form(data)
        if form.is_valid():
            restaurant = form.save()
        else:
            self.fail('Errors found on form:%s' % form_set)

        form_set = FormSet(data, instance=restaurant)
        if form_set.is_valid():
            form_set.save()
            manager = Manager.objects.all().values()
            self.astertEqual(manager[0]['name'], 'Guido Van Rossum')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

        # Now update the Manager instance
        data = {
            'manager_set-TOTAL_FORMS': '1',
            'manager_set-INITIAL_FORMS': '1',
            'manager_set-MAX_NUM_FORMS': '0',
            'manager_set-0-id': str(manager[0]['id']),
            'manager_set-0-name': 'Terry Gilliam'
        }
        form_set = FormSet(data, instance=restaurant)
        if form_set.is_valid():
            form_set.save()
            manager = Manager.objects.all().values()
            self.astertEqual(manager[0]['name'], 'Terry Gilliam')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

        # Now add a new Manager instance
        data = {
            'manager_set-TOTAL_FORMS': '2',
            'manager_set-INITIAL_FORMS': '1',
            'manager_set-MAX_NUM_FORMS': '0',
            'manager_set-0-id': str(manager[0]['id']),
            'manager_set-0-name': 'Terry Gilliam',
            'manager_set-1-name': 'John Cleese'
        }
        form_set = FormSet(data, instance=restaurant)
        if form_set.is_valid():
            form_set.save()
            manager = Manager.objects.all().values().order_by('name')
            self.astertEqual(manager[0]['name'], 'John Cleese')
            self.astertEqual(manager[1]['name'], 'Terry Gilliam')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_save_as_new_with_new_inlines(self):
        """
        Existing and new inlines are saved with save_as_new.

        Regression for #14938.
        """
        efnet = Network.objects.create(name="EFNet")
        host1 = Host.objects.create(hostname="irc.he.net", network=efnet)

        HostFormSet = inlineformset_factory(Network, Host, fields="__all__")

        # Add a new host, modify previous host, and save-as-new
        data = {
            'host_set-TOTAL_FORMS': '2',
            'host_set-INITIAL_FORMS': '1',
            'host_set-MAX_NUM_FORMS': '0',
            'host_set-0-id': str(host1.id),
            'host_set-0-hostname': 'tranquility.hub.dal.net',
            'host_set-1-hostname': 'matrix.de.eu.dal.net'
        }

        # To save a formset as new, it needs a new hub instance
        dalnet = Network.objects.create(name="DALnet")
        formset = HostFormSet(data, instance=dalnet, save_as_new=True)

        self.astertTrue(formset.is_valid())
        formset.save()
        self.astertQuerysetEqual(
            dalnet.host_set.order_by("hostname"),
            ["<Host: matrix.de.eu.dal.net>", "<Host: tranquility.hub.dal.net>"]
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inlineformset_custom_callback(self):
        callback = Callback()
        inlineformset_factory(User, UserSite, form=UserSiteForm,
                              formfield_callback=callback, fields="__all__")
        self.astertCallbackCalled(callback)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_resubmit(self):
        u = User.objects.create(username='foo', serial=1)
        us = UserSite.objects.create(user=u, data=7)
        formset_cls = inlineformset_factory(User, UserSite, fields="__all__")
        data = {
            'serial': '1',
            'username': 'foo',
            'usersite_set-TOTAL_FORMS': '1',
            'usersite_set-INITIAL_FORMS': '1',
            'usersite_set-MAX_NUM_FORMS': '1',
            'usersite_set-0-id': str(us.pk),
            'usersite_set-0-data': '7',
            'usersite_set-0-user': 'foo',
            'usersite_set-0-DELETE': '1'
        }
        formset = formset_cls(data, instance=u)
        self.astertTrue(formset.is_valid())
        formset.save()
        self.astertEqual(UserSite.objects.count(), 0)
        formset = formset_cls(data, instance=u)
        # Even if the "us" object isn't in the DB any more, the form
        # validates.
        self.astertTrue(formset.is_valid())
        formset.save()
        self.astertEqual(UserSite.objects.count(), 0)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_delete_already_deleted(self):
        u = User.objects.create(username='foo', serial=1)
        us = UserSite.objects.create(user=u, data=7)
        formset_cls = inlineformset_factory(User, UserSite, fields="__all__")
        data = {
            'serial': '1',
            'username': 'foo',
            'usersite_set-TOTAL_FORMS': '1',
            'usersite_set-INITIAL_FORMS': '1',
            'usersite_set-MAX_NUM_FORMS': '1',
            'usersite_set-0-id': str(us.pk),
            'usersite_set-0-data': '7',
            'usersite_set-0-user': 'foo',
            'usersite_set-0-DELETE': '1'
        }
        formset = formset_cls(data, instance=u)
        us.delete()
        self.astertTrue(formset.is_valid())
        formset.save()
        self.astertEqual(UserSite.objects.count(), 0)

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : studybuffalo
    def get(self, request, *args, **kwargs):
        """Overriding get method to handle inline formset."""
        # Setup the formset for PlanCost
        PlanCostFormSet = inlineformset_factory( # pylint: disable=invalid-name
            parent_model=models.SubscriptionPlan,
            model=models.PlanCost,
            form=forms.PlanCostForm,
            can_delete=False,
            extra=1,
        )

        self.object = None
        form = self.get_form(self.get_form_clast())
        cost_forms = PlanCostFormSet()

        return self.render_to_response(
            self.get_context_data(
                form=form,
                cost_forms=cost_forms,
            )
        )

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : studybuffalo
    def get(self, request, *args, **kwargs):
        """Overriding get method to handle inline formset."""
        # Setup the formset for PlanCost
        PlanCostFormSet = inlineformset_factory( # pylint: disable=invalid-name
            parent_model=models.SubscriptionPlan,
            model=models.PlanCost,
            form=forms.PlanCostForm,
            can_delete=True,
            extra=1,
        )

        self.object = self.get_object()
        form = self.get_form(self.get_form_clast())
        cost_forms = PlanCostFormSet(instance=self.object)

        return self.render_to_response(
            self.get_context_data(
                form=form,
                cost_forms=cost_forms,
            )
        )