Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fixed #17527 -- Improved exception message when adding the wrong type…

… of object to a ManyToManyField. Thanks, guettli and cClaude Paroz.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17437 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 2b0c1ea64155bd3f825b06e266d73c00dbf4196f 1 parent 56d787d
Jannis Leidel jezdez authored
4 django/db/models/fields/related.py
View
@@ -474,7 +474,7 @@ def get_prefetch_query_set(self, instances):
def add(self, *objs):
for obj in objs:
if not isinstance(obj, self.model):
- raise TypeError("'%s' instance expected" % self.model._meta.object_name)
+ raise TypeError("'%s' instance expected, got %r" % (self.model._meta.object_name, obj))
setattr(obj, rel_field.name, self.instance)
obj.save()
add.alters_data = True
@@ -636,7 +636,7 @@ def _add_items(self, source_field_name, target_field_name, *objs):
(obj, self.instance._state.db, obj._state.db))
new_ids.add(obj.pk)
elif isinstance(obj, Model):
- raise TypeError("'%s' instance expected" % self.model._meta.object_name)
+ raise TypeError("'%s' instance expected, got %r" % (self.model._meta.object_name, obj))
else:
new_ids.add(obj)
db = router.db_for_write(self.through, instance=self.instance)
5 tests/modeltests/many_to_many/tests.py
View
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, with_statement
from django.test import TestCase
@@ -52,7 +52,8 @@ def test_add(self):
])
# Adding an object of the wrong type raises TypeError
- self.assertRaises(TypeError, a6.publications.add, a5)
+ with self.assertRaisesRegexp(TypeError, "'Publication' instance expected, got <Article.*"):
+ a6.publications.add(a5)
# Add a Publication directly via publications.add by using keyword arguments.
p4 = a6.publications.create(title='Highlights for Adults')
self.assertQuerysetEqual(a6.publications.all(),
5 tests/modeltests/many_to_one/tests.py
View
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, with_statement
from copy import deepcopy
from datetime import datetime
@@ -68,7 +68,8 @@ def test_add(self):
self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"])
# Adding an object of the wrong type raises TypeError.
- self.assertRaises(TypeError, self.r.article_set.add, self.r2)
+ with self.assertRaisesRegexp(TypeError, "'Article' instance expected, got <Reporter.*"):
+ self.r.article_set.add(self.r2)
self.assertQuerysetEqual(self.r.article_set.all(),
[
"<Article: John's second story>",
Please sign in to comment.
Something went wrong with that request. Please try again.