Commits

Waldemar Kornewald committed 640a13a

Adds a test case for nice TypeErrors in EmbeddedModelField's seriaization method, plus one fix to make the tests pass (nice error messages should also be used in the "untyped" case) Contributed by Jonas Haag.

Comments (0)

Files changed (2)

djangotoolbox/fields.py

         embedded_instance = super(EmbeddedModelField, self).pre_save(model_instance, add)
         if embedded_instance is None:
             return None, None
-        if self.embedded_model is not None and \
-                not isinstance(embedded_instance, self.embedded_model):
-            raise TypeError("Expected instance of type %r, not %r"
-                            % (type(self.embedded_model), type(embedded_instance)))
+
+        model = self.embedded_model or models.Model
+        if not isinstance(embedded_instance, model):
+            raise TypeError("Expected instance of type %r, not %r" % (
+                            type(model), type(embedded_instance)))
 
         data = dict((field.name, field.pre_save(embedded_instance, add))
                     for field in embedded_instance._meta.fields)

djangotoolbox/tests.py

 
     class EmbeddedModelFieldModel(models.Model):
         simple = EmbeddedModelField('EmbeddedModel', null=True)
+        simple_untyped = EmbeddedModelField(null=True)
         typed_list = ListField(EmbeddedModelField('SetModel'))
         untyped_list = ListField(EmbeddedModelField())
         untyped_dict = DictField(EmbeddedModelField())
         self.assertEqual(instance.simple.auto_now_add, auto_now_add)
         self.assertGreater(instance.simple.auto_now, auto_now)
 
+    def test_error_messages(self):
+        for kwargs in (
+            {'simple_untyped' : 42},
+            {'simple' : 42}
+        ):
+            self.assertRaisesRegexp(TypeError, "Expected instance of type",
+                                    EmbeddedModelFieldModel(**kwargs).save)
+
     def test_typed_listfield(self):
         EmbeddedModelFieldModel.objects.create(
             typed_list=[SetModel(setfield=range(3)), SetModel(setfield=range(9))]