Python django.forms.formsets.BaseFormSet() Examples

The following are 9 code examples of django.forms.formsets.BaseFormSet(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.forms.formsets , or try the search function .
Example #1
Source File: test_formsets.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_empty_formset_is_valid(self):
        """An empty formset still calls clean()"""
        class EmptyFsetWontValidate(BaseFormSet):
            def clean(self):
                raise ValidationError('Clean method called')

        EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate)
        formset = EmptyFsetWontValidateFormset(
            data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '0'},
            prefix="form",
        )
        formset2 = EmptyFsetWontValidateFormset(
            data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '1', 'form-0-name': 'bah'},
            prefix="form",
        )
        self.assertFalse(formset.is_valid())
        self.assertFalse(formset2.is_valid()) 
Example #2
Source File: test_formsets.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_empty_formset_is_valid(self):
        """An empty formset still calls clean()"""
        class EmptyFsetWontValidate(BaseFormSet):
            def clean(self):
                raise ValidationError('Clean method called')

        EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate)
        formset = EmptyFsetWontValidateFormset(
            data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '0'},
            prefix="form",
        )
        formset2 = EmptyFsetWontValidateFormset(
            data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '1', 'form-0-name': 'bah'},
            prefix="form",
        )
        self.assertFalse(formset.is_valid())
        self.assertFalse(formset2.is_valid()) 
Example #3
Source File: test_formsets.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_form_kwargs_formset_dynamic(self):
        """Form kwargs can be passed dynamically in a formset."""
        class DynamicBaseFormSet(BaseFormSet):
            def get_form_kwargs(self, index):
                return {'custom_kwarg': index}

        DynamicFormSet = formset_factory(CustomKwargForm, formset=DynamicBaseFormSet, extra=2)
        formset = DynamicFormSet(form_kwargs={'custom_kwarg': 'ignored'})
        for i, form in enumerate(formset):
            self.assertTrue(hasattr(form, 'custom_kwarg'))
            self.assertEqual(form.custom_kwarg, i) 
Example #4
Source File: test_formsets.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_formset_iteration(self):
        """Formset instances are iterable."""
        ChoiceFormset = formset_factory(Choice, extra=3)
        formset = ChoiceFormset()
        # An iterated formset yields formset.forms.
        forms = list(formset)
        self.assertEqual(forms, formset.forms)
        self.assertEqual(len(formset), len(forms))
        # A formset may be indexed to retrieve its forms.
        self.assertEqual(formset[0], forms[0])
        with self.assertRaises(IndexError):
            formset[3]

        # Formsets can override the default iteration order
        class BaseReverseFormSet(BaseFormSet):
            def __iter__(self):
                return reversed(self.forms)

            def __getitem__(self, idx):
                return super().__getitem__(len(self) - idx - 1)

        ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3)
        reverse_formset = ReverseChoiceFormset()
        # __iter__() modifies the rendering order.
        # Compare forms from "reverse" formset with forms from original formset
        self.assertEqual(str(reverse_formset[0]), str(forms[-1]))
        self.assertEqual(str(reverse_formset[1]), str(forms[-2]))
        self.assertEqual(len(reverse_formset), len(forms)) 
Example #5
Source File: test_formsets.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_non_form_errors_run_full_clean(self):
        """
        If non_form_errors() is called without calling is_valid() first,
        it should ensure that full_clean() is called.
        """
        class BaseCustomFormSet(BaseFormSet):
            def clean(self):
                raise ValidationError("This is a non-form error")

        ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet)
        formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
        self.assertIsInstance(formset.non_form_errors(), ErrorList)
        self.assertEqual(list(formset.non_form_errors()), ['This is a non-form error']) 
Example #6
Source File: test_formsets.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_form_kwargs_formset_dynamic(self):
        """Form kwargs can be passed dynamically in a formset."""
        class DynamicBaseFormSet(BaseFormSet):
            def get_form_kwargs(self, index):
                return {'custom_kwarg': index}

        DynamicFormSet = formset_factory(CustomKwargForm, formset=DynamicBaseFormSet, extra=2)
        formset = DynamicFormSet(form_kwargs={'custom_kwarg': 'ignored'})
        for i, form in enumerate(formset):
            self.assertTrue(hasattr(form, 'custom_kwarg'))
            self.assertEqual(form.custom_kwarg, i) 
Example #7
Source File: test_formsets.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_non_form_errors_run_full_clean(self):
        """
        If non_form_errors() is called without calling is_valid() first,
        it should ensure that full_clean() is called.
        """
        class BaseCustomFormSet(BaseFormSet):
            def clean(self):
                raise ValidationError("This is a non-form error")

        ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet)
        formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
        self.assertIsInstance(formset.non_form_errors(), ErrorList)
        self.assertEqual(list(formset.non_form_errors()), ['This is a non-form error']) 
Example #8
Source File: test_views.py    From Food-Pantry-Inventory with MIT License 4 votes vote down vote up
def test_post_pallet_select_name_form(self):

        user = create_user('alice', 'shrock')

        client = Client()
        client.force_login(user)

        # -------------------
        # No pallet selected
        # -------------------
        response = client.post(
            self.url,
            {
                'form_name': BuildPalletView.PALLET_SELECT_FORM_NAME,
            }
        )
        self.assertEqual(
            400,
            response.status_code,
            response.content.decode(),
        )
        self.assertIsInstance(
            response.context.get('pallet_select_form'),
            PalletSelectForm,
        )

        # -------------------------------------------------
        # Pallet selected
        # -------------------------------------------------
        pallet = Pallet.objects.create(name="test pallet")

        response = client.post(
            self.url,
            {
                'form_name': BuildPalletView.PALLET_SELECT_FORM_NAME,
                'pallet': pallet.pk
            }
        )
        self.assertEqual(200, response.status_code)

        build_pallet_form = response.context.get('form')
        box_forms = response.context.get('box_forms')
        pallet_form = response.context.get('pallet_form')

        self.assertIsInstance(build_pallet_form, BuildPalletForm)
        self.assertIsInstance(box_forms, BaseFormSet)
        self.assertIsInstance(pallet_form, HiddenPalletForm)

        pallet_form = response.context.get('pallet_form')
        self.assertIsInstance(pallet_form, HiddenPalletForm)

        pallet_from_context = pallet_form.initial.get('pallet')
        self.assertEqual(pallet, pallet_from_context)
        self.assertEqual(Pallet.FILL, pallet_from_context.pallet_status) 
Example #9
Source File: test_views.py    From Food-Pantry-Inventory with MIT License 4 votes vote down vote up
def test_post_pallet_name_form(self):

        user = create_user('doug', 'state')

        client = Client()
        client.force_login(user)

        # -----------------------
        # No pallet name entered
        # -----------------------
        response = client.post(
            self.url,
            {
                'form_name': BuildPalletView.PALLET_NAME_FORM_NAME,
            }
        )
        self.assertEqual(400, response.status_code)
        self.assertIsInstance(
            response.context.get('pallet_name_form'),
            PalletNameForm,
        )

        # -------------------------------------------------
        # pallet name supplied
        # -------------------------------------------------
        pallet_name = "nuevo palet"
        response = client.post(
            self.url,
            {
                'form_name': BuildPalletView.PALLET_NAME_FORM_NAME,
                'name': pallet_name,
            }
        )
        self.assertEqual(200, response.status_code)

        build_pallet_form = response.context.get('form')
        box_forms = response.context.get('box_forms')
        pallet_form = response.context.get('pallet_form')

        self.assertIsInstance(build_pallet_form, BuildPalletForm)
        self.assertIsInstance(box_forms, BaseFormSet)
        self.assertIsInstance(pallet_form, HiddenPalletForm)

        pallet_form = response.context.get('pallet_form')
        self.assertIsInstance(pallet_form, HiddenPalletForm)

        pallet = pallet_form.initial.get('pallet')
        self.assertEqual(
            Pallet.objects.get(name=pallet_name),
            pallet,
        )
        self.assertEqual(Pallet.FILL, pallet.pallet_status)