Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #14099 - BaseModelFormSet should use _should_delete_form

Thanks to kenth for the report and patch.

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

0 notes on commit 13f9fd3

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