From 91b9d0b2a3fa55ff163f64bc689a59ca01cff8bb Mon Sep 17 00:00:00 2001 From: Craig Blaszczyk Date: Fri, 8 Jul 2011 18:14:52 +0100 Subject: [PATCH] remove hardcoded model._meta.many_to_many[0]; update mixin tests to test with 0, 1, or multiple groups --- djangorestframework/mixins.py | 3 +-- djangorestframework/tests/mixins.py | 38 ++++++++++++++++++++++++++--- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/djangorestframework/mixins.py b/djangorestframework/mixins.py index 9f65625e7..b1c0d815b 100644 --- a/djangorestframework/mixins.py +++ b/djangorestframework/mixins.py @@ -524,8 +524,7 @@ class CreateModelMixin(object): for field in model._meta.many_to_many: if content.has_key(field.name): m2m_data[field.name] = ( - model._meta.many_to_many[0].m2m_reverse_field_name(), - content[field.name] + field.m2m_reverse_field_name(), content[field.name] ) del content[field.name] diff --git a/djangorestframework/tests/mixins.py b/djangorestframework/tests/mixins.py index 1e8bf410e..b9aa4c3bf 100644 --- a/djangorestframework/tests/mixins.py +++ b/djangorestframework/tests/mixins.py @@ -63,11 +63,23 @@ class TestModelCreation(TestCase): def url(self, instance): return "/customusers/%i" % instance.id + + form_data = {'username': 'bar0', 'groups': []} + request = self.req.post('/groups', data=form_data) + cleaned_data = dict(form_data) + cleaned_data['groups'] = [] + mixin = CreateModelMixin() + mixin.resource = UserResource + mixin.CONTENT = cleaned_data - group = Group(name='foo') + response = mixin.post(request) + self.assertEquals(1, CustomUser.objects.count()) + self.assertEquals(0, response.cleaned_content.groups.count()) + + group = Group(name='foo1') group.save() - form_data = {'username': 'bar', 'groups': [group.id]} + form_data = {'username': 'bar1', 'groups': [group.id]} request = self.req.post('/groups', data=form_data) cleaned_data = dict(form_data) cleaned_data['groups'] = [group] @@ -76,8 +88,26 @@ class TestModelCreation(TestCase): mixin.CONTENT = cleaned_data response = mixin.post(request) - self.assertEquals(1, CustomUser.objects.count()) + self.assertEquals(2, CustomUser.objects.count()) self.assertEquals(1, response.cleaned_content.groups.count()) - self.assertEquals('foo', response.cleaned_content.groups.all()[0].name) + self.assertEquals('foo1', response.cleaned_content.groups.all()[0].name) + + + group2 = Group(name='foo2') + group2.save() + + form_data = {'username': 'bar2', 'groups': [group.id, group2.id]} + request = self.req.post('/groups', data=form_data) + cleaned_data = dict(form_data) + cleaned_data['groups'] = [group, group2] + mixin = CreateModelMixin() + mixin.resource = UserResource + mixin.CONTENT = cleaned_data + + response = mixin.post(request) + self.assertEquals(3, CustomUser.objects.count()) + self.assertEquals(2, response.cleaned_content.groups.count()) + self.assertEquals('foo', response.cleaned_content.groups.all()[0].name) + self.assertEquals('foo2', response.cleaned_content.groups.all()[1].name)