Ticket #17155: 17155-test.diff

File 17155-test.diff, 1.5 KB (added by Claude Paroz, 13 years ago)

Test custom clean with model formsets

  • tests/regressiontests/model_formsets_regress/tests.py

    diff --git a/tests/regressiontests/model_formsets_regress/tests.py b/tests/regressiontests/model_formsets_regress/tests.py
    index 35a794a..3ecf3e3 100644
    a b class FormsetTests(TestCase):  
    230230            self.assertTrue(isinstance(form.errors, ErrorDict))
    231231            self.assertTrue(isinstance(form.non_field_errors(), ErrorList))
    232232
     233    def test_clean_applies_to_model(self):
     234        '''
     235        Test that value modified in custom form clean() method is applied to saved models
     236        '''
     237        class UserFormWithClean(forms.ModelForm):
     238            class Meta:
     239                model = User
     240
     241            def clean(self):
     242                self.cleaned_data['serial'] += 1
     243                return self.cleaned_data
     244
     245        Formset = modelformset_factory(User, form=UserFormWithClean)
     246        data = {
     247            'form-TOTAL_FORMS': u'2',
     248            'form-INITIAL_FORMS': u'0',
     249            'form-MAX_NUM_FORMS': u'0',
     250            'form-0-id': '',
     251            'form-0-username': u'apollo12',
     252            'form-0-serial': u'1',
     253            'form-1-id': '',
     254            'form-1-username': u'apollo13',
     255            'form-1-serial': u'2',
     256        }
     257        formset = Formset(data)
     258        self.assertTrue(formset.is_valid())
     259        users = formset.save()
     260        self.assertEqual(users[-1].serial, 3)
     261
     262
    233263class CustomWidget(forms.CharField):
    234264    pass
    235265
Back to Top