Commits

James Crasta committed 5577125

Make 'del' on a Form idempotent. Fixes #174.

Comments (0)

Files changed (2)

         # Try deleting a nonexistent field
         self.assertRaises(AttributeError, form.__delattr__, 'fake')
 
+    def test_delattr_idempotency(self):
+        form = self.F()
+        del form.test
+        self.assertEqual(form.test, None)
+
+        # Make sure deleting a normal attribute works
+        form.foo = 9
+        del form.foo
+        self.assertRaises(AttributeError, form.__delattr__, 'foo')
+
+        # Check idempotency
+        del form.test
+        self.assertEqual(form.test, None)
+
     def test_ordered_fields(self):
         class MyForm(Form):
             strawberry = TextField()
         setattr(self, name, None)
 
     def __delattr__(self, name):
-        try:
+        if name in self._fields:
             self.__delitem__(name)
-        except KeyError:
-            super(Form, self).__delattr__(name)
+        else:
+            # This is done for idempotency, if we have a name which is a field,
+            # we want to mask it by setting the value to None.
+            unbound_field = getattr(self.__class__, name, None)
+            if unbound_field is not None and hasattr(unbound_field, '_formfield'):
+                setattr(self, name, None)
+            else:
+                super(Form, self).__delattr__(name)
 
     def validate(self):
         """