无法在Django中添加/测试对象添加到ManyToMany关系

时间:2015-05-16 16:22:12

标签: django

我有以下观点;

class MemberAdd(View): 
    def get(self, request):
        raise Http404

    def post(self, request, pk):
        form = AddMemberForm(request.POST)
        if form.is_valid():
            Station.objects.get(pk=pk).members.add(
                form.cleaned_data['user']
            )
            return HttpResponseRedirect(reverse("home_station",
                                        kwargs={'pk':pk},
                                        )
                                )

AddMemberForm;

class AddMemberForm(Form):
    user = forms.ModelChoiceField(queryset=User.objects.all(),
                                  empty_label='Choose a User',
    )

正如您在添加到ManyToMany关系后所看到的那样,视图会重定向到我作为特定模型对象的主页的页面。我在其中列出了ManyToMany关系中的对象,我确实在那里找到了新添加的对象。

但是当我运行以下测试时;

class TestStationManagement(TestCase):
    .
    .
    .    
    def test_add_member(self):
        """
        Tests addition of a member to station
        """
        user1 = User.objects.create_user(username='someusername',
                                        password='somepassword')
        user1.save()
        station = Station.objects.create(name='somename',
                                         address='someaddress',
                                         owner=user1)
        station.save()
        user2 = User.objects.create_user(username='someotherusername',
                                        password='someotherpassword')
        user2.save()
        self.client.post(reverse('add_member',
                                 kwargs={'pk':station.pk}),
                         {'user':user2},
                         follow=True)
        self.assertIn(user2, station.members.all())

我收到断言错误E AssertionError: <User: someotherusername> not found in []

看到错误?请帮忙。

2 个答案:

答案 0 :(得分:1)

您必须发送用户的ID。

这可能有效:

add_member_post = self.client.post(reverse('add_member',
                                 kwargs={'pk':station.pk}),
                         {'user':user2.id},
                         follow=True)

检查请求是否确实有效:

self.assertEqual(add_member_post.status_code, 200)

答案 1 :(得分:0)

self.client.post(...) station = Station.objects.get(pk=station.pk) self.assertIn(...) 仍然是您在测试中创建的实例,并且不会受到视图中发生的任何事情的影响。您需要从数据库重新加载它:

{{1}}