Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

[1.2.X] Fixed #14099 - BaseModelFormSet should use _should_delete_form

Thanks to kenth for the report and patch.

Backport of [15612] from trunk.

git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.2.X@15613 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit c326ec48d834eb8128ac20a37cb647fdfa769ae6 1 parent 4df0e5f
Luke Plant authored February 21, 2011
20  django/forms/models.py
@@ -16,7 +16,7 @@
16 16
 from fields import Field, ChoiceField
17 17
 from widgets import SelectMultiple, HiddenInput, MultipleHiddenInput
18 18
 from widgets import media_property
19  
-from formsets import BaseFormSet, formset_factory, DELETION_FIELD_NAME
  19
+from formsets import BaseFormSet, formset_factory
20 20
 
21 21
 __all__ = (
22 22
     'ModelForm', 'BaseModelForm', 'model_to_dict', 'fields_for_model',
@@ -599,13 +599,10 @@ def save_existing_objects(self, commit=True):
599 599
             pk_value = getattr(pk_value, 'pk', pk_value)
600 600
 
601 601
             obj = self._existing_object(pk_value)
602  
-            if self.can_delete:
603  
-                raw_delete_value = form._raw_value(DELETION_FIELD_NAME)
604  
-                should_delete = form.fields[DELETION_FIELD_NAME].clean(raw_delete_value)
605  
-                if should_delete:
606  
-                    self.deleted_objects.append(obj)
607  
-                    obj.delete()
608  
-                    continue
  602
+            if self.can_delete and self._should_delete_form(form):
  603
+                self.deleted_objects.append(obj)
  604
+                obj.delete()
  605
+                continue
609 606
             if form.has_changed():
610 607
                 self.changed_objects.append((obj, form.changed_data))
611 608
                 saved_instances.append(self.save_existing(form, obj, commit=commit))
@@ -620,11 +617,8 @@ def save_new_objects(self, commit=True):
620 617
                 continue
621 618
             # If someone has marked an add form for deletion, don't save the
622 619
             # object.
623  
-            if self.can_delete:
624  
-                raw_delete_value = form._raw_value(DELETION_FIELD_NAME)
625  
-                should_delete = form.fields[DELETION_FIELD_NAME].clean(raw_delete_value)
626  
-                if should_delete:
627  
-                    continue
  620
+            if self.can_delete and self._should_delete_form(form):
  621
+                continue
628 622
             self.new_objects.append(self.save_new(form, commit=commit))
629 623
             if not commit:
630 624
                 self.saved_forms.append(form)
124  tests/regressiontests/model_formsets_regress/tests.py
... ...
@@ -1,6 +1,7 @@
1 1
 from django import forms
  2
+from django.forms.formsets import BaseFormSet, DELETION_FIELD_NAME
2 3
 from django.forms.util import ErrorDict, ErrorList
3  
-from django.forms.models import modelform_factory, inlineformset_factory, modelformset_factory
  4
+from django.forms.models import modelform_factory, inlineformset_factory, modelformset_factory, BaseModelFormSet
4 5
 from django.test import TestCase
5 6
 
6 7
 from models import User, UserSite, Restaurant, Manager, Network, Host
@@ -275,3 +276,124 @@ def test_modelformset_custom_callback(self):
275 276
         modelformset_factory(UserSite, form=UserSiteForm,
276 277
                              formfield_callback=callback)
277 278
         self.assertCallbackCalled(callback)
  279
+
  280
+
  281
+class BaseCustomDeleteFormSet(BaseFormSet):
  282
+    """
  283
+    A formset mix-in that lets a form decide if it's to be deleted.
  284
+    Works for BaseFormSets. Also works for ModelFormSets with #14099 fixed.
  285
+
  286
+    form.should_delete() is called. The formset delete field is also suppressed.
  287
+    """
  288
+    def add_fields(self, form, index):
  289
+        super(BaseCustomDeleteFormSet, self).add_fields(form, index)
  290
+        self.can_delete = True
  291
+        if DELETION_FIELD_NAME in form.fields:
  292
+            del form.fields[DELETION_FIELD_NAME]
  293
+
  294
+    def _should_delete_form(self, form):
  295
+        return hasattr(form, 'should_delete') and form.should_delete()
  296
+
  297
+
  298
+class FormfieldShouldDeleteFormTests(TestCase):
  299
+    """
  300
+    Regression for #14099: BaseModelFormSet should use ModelFormSet method _should_delete_form
  301
+    """
  302
+
  303
+    class BaseCustomDeleteModelFormSet(BaseModelFormSet, BaseCustomDeleteFormSet):
  304
+        """ Model FormSet with CustomDelete MixIn """
  305
+
  306
+    class CustomDeleteUserForm(forms.ModelForm):
  307
+        """ A model form with a 'should_delete' method """
  308
+        class Meta:
  309
+            model = User
  310
+
  311
+        def should_delete(self):
  312
+            """ delete form if odd PK """
  313
+            return self.instance.id % 2 != 0
  314
+
  315
+    NormalFormset = modelformset_factory(User, form=CustomDeleteUserForm, can_delete=True)
  316
+    DeleteFormset = modelformset_factory(User, form=CustomDeleteUserForm, formset=BaseCustomDeleteModelFormSet)
  317
+
  318
+    data = {
  319
+            'form-TOTAL_FORMS': '4',
  320
+            'form-INITIAL_FORMS': '0',
  321
+            'form-MAX_NUM_FORMS': '4',
  322
+            'form-0-username': 'John',
  323
+            'form-0-serial': '1',
  324
+            'form-1-username': 'Paul',
  325
+            'form-1-serial': '2',
  326
+            'form-2-username': 'George',
  327
+            'form-2-serial': '3',
  328
+            'form-3-username': 'Ringo',
  329
+            'form-3-serial': '5',
  330
+            }
  331
+
  332
+    bound_ids = {
  333
+            'form-INITIAL_FORMS': '4',
  334
+            'form-0-id': '1',
  335
+            'form-1-id': '2',
  336
+            'form-2-id': '3',
  337
+            'form-3-id': '4',
  338
+            }
  339
+
  340
+    delete_all_ids = {
  341
+            'form-0-DELETE': '1',
  342
+            'form-1-DELETE': '1',
  343
+            'form-2-DELETE': '1',
  344
+            'form-3-DELETE': '1',
  345
+            }
  346
+
  347
+    def test_init_database(self):
  348
+        """ Add test data to database via formset """
  349
+        formset = self.NormalFormset(self.data)
  350
+        self.assertTrue(formset.is_valid())
  351
+        self.assertEqual(len(formset.save()), 4)
  352
+
  353
+    def test_no_delete(self):
  354
+        """ Verify base formset doesn't modify database """
  355
+        # reload database
  356
+        self.test_init_database()
  357
+
  358
+        # pass standard data dict & see none updated
  359
+        data = dict(self.data)
  360
+        data.update(self.bound_ids)
  361
+        formset = self.NormalFormset(data, queryset=User.objects.all())
  362
+        self.assertTrue(formset.is_valid())
  363
+        self.assertEqual(len(formset.save()), 0)
  364
+        self.assertEqual(len(User.objects.all()), 4)
  365
+
  366
+    def test_all_delete(self):
  367
+        """ Verify base formset honors DELETE field """
  368
+        # reload database
  369
+        self.test_init_database()
  370
+
  371
+        # create data dict with all fields marked for deletion
  372
+        data = dict(self.data)
  373
+        data.update(self.bound_ids)
  374
+        data.update(self.delete_all_ids)
  375
+        formset = self.NormalFormset(data, queryset=User.objects.all())
  376
+        self.assertTrue(formset.is_valid())
  377
+        self.assertEqual(len(formset.save()), 0)
  378
+        self.assertEqual(len(User.objects.all()), 0)
  379
+
  380
+    def test_custom_delete(self):
  381
+        """ Verify DeleteFormset ignores DELETE field and uses form method """
  382
+        # reload database
  383
+        self.test_init_database()
  384
+
  385
+        # Create formset with custom Delete function
  386
+        # create data dict with all fields marked for deletion
  387
+        data = dict(self.data)
  388
+        data.update(self.bound_ids)
  389
+        data.update(self.delete_all_ids)
  390
+        formset = self.DeleteFormset(data, queryset=User.objects.all())
  391
+
  392
+        # verify two were deleted
  393
+        self.assertTrue(formset.is_valid())
  394
+        self.assertEqual(len(formset.save()), 0)
  395
+        self.assertEqual(len(User.objects.all()), 2)
  396
+
  397
+        # verify no "odd" PKs left
  398
+        odd_ids = [user.id for user in User.objects.all() if user.id % 2]
  399
+        self.assertEqual(len(odd_ids), 0)

0 notes on commit c326ec4

Please sign in to comment.
Something went wrong with that request. Please try again.