diff options
| author | Sergei Maertens <sergei@maykinmedia.nl> | 2015-06-04 12:47:43 +0200 |
|---|---|---|
| committer | Sergei Maertens <sergei@maykinmedia.nl> | 2015-06-04 15:13:55 +0200 |
| commit | 238e2ac3690755d0e6c2dfca815e2b6f84a47f6e (patch) | |
| tree | e7147d51bb64e769b7c7030e0cc00319a2d6c5f7 /tests | |
| parent | 57dbc87ade5533d78089690ec7795034ff69177a (diff) | |
Fixed #18166 -- Added form_kwargs support to formsets.
By specifying form_kwargs when instantiating the formset, or overriding
the `get_form_kwargs` method on a formset class, you can pass extra
keyword arguments to the underlying `Form` instances.
Includes tests and documentation update.
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/forms_tests/tests/test_formsets.py | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py index 0bd28111e1..0fea84a782 100644 --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -57,6 +57,12 @@ class SplitDateTimeForm(Form): SplitDateTimeFormSet = formset_factory(SplitDateTimeForm) +class CustomKwargForm(Form): + def __init__(self, *args, **kwargs): + self.custom_kwarg = kwargs.pop('custom_kwarg') + super(CustomKwargForm, self).__init__(*args, **kwargs) + + class FormsFormsetTestCase(SimpleTestCase): def make_choiceformset(self, formset_data=None, formset_class=ChoiceFormSet, @@ -114,6 +120,37 @@ class FormsFormsetTestCase(SimpleTestCase): self.assertFalse(formset.is_valid()) self.assertFalse(formset.has_changed()) + def test_form_kwargs_formset(self): + """ + Test that custom kwargs set on the formset instance are passed to the + underlying forms. + """ + FormSet = formset_factory(CustomKwargForm, extra=2) + formset = FormSet(form_kwargs={'custom_kwarg': 1}) + for form in formset: + self.assertTrue(hasattr(form, 'custom_kwarg')) + self.assertEqual(form.custom_kwarg, 1) + + def test_form_kwargs_formset_dynamic(self): + """ + Test that 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) + + def test_form_kwargs_empty_form(self): + FormSet = formset_factory(CustomKwargForm) + formset = FormSet(form_kwargs={'custom_kwarg': 1}) + self.assertTrue(hasattr(formset.empty_form, 'custom_kwarg')) + self.assertEqual(formset.empty_form.custom_kwarg, 1) + def test_formset_validation(self): # FormSet instances can also have an error attribute if validation failed for # any of the forms. |
