Ticket #14394: validate_bad_data_assignment_to_m2m.patch

File validate_bad_data_assignment_to_m2m.patch, 1.7 KB (added by Igor Sobreira, 14 years ago)
  • django/db/models/fields/related.py

     
    727727        if not self.field.rel.through._meta.auto_created:
    728728            opts = self.field.rel.through._meta
    729729            raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model.  Use %s.%s's Manager instead." % (opts.app_label, opts.object_name))
     730       
     731        if not isinstance(value, (list, tuple)):
     732            raise TypeError(u"Cannot set %s values on a ManyToManyField. Only lists or tuples (or subclasses) allowed." % type(value))
    730733
    731734        manager = self.__get__(instance)
    732735        manager.clear()
  • tests/regressiontests/m2m_regress/tests.py

     
    7373
    7474        self.assertQuerysetEqual(c1.tags.all(), ["<Tag: t1>", "<Tag: t2>"])
    7575        self.assertQuerysetEqual(t1.tag_collections.all(), ["<TagCollection: c1>"])
     76
     77    def test_assigning_invalid_data_to_m2m_doesnt_clear_existing_relations(self):
     78       
     79        t1 = Tag.objects.create(name='t1')
     80        t2 = Tag.objects.create(name='t2')
     81       
     82        c1 = TagCollection.objects.create(name='c1')
     83        c1.tags = [t1,t2]
     84       
     85        def invalid_assigment():
     86            c1.tags = 7
     87
     88        self.assertRaises(TypeError, invalid_assigment)
     89
     90        c1 = TagCollection.objects.get(pk=c1.pk)
     91
     92        self.assertQuerysetEqual(c1.tags.all(), ["<Tag: t1>", "<Tag: t2>"])
     93
     94
Back to Top