来自Django模型的对象的传递ID

时间:2019-04-26 10:20:54

标签: python django

这是我的test

def someTest(self):

        # create an object 
        sampleModel.objects.create(unique_id='999999')

        # add code here to pass the sampleModel object created above to view:page1

        # Make sure the sampleModel object created appears in page 1
        response = self.client.get(reverse('view:page1'))  # check that above created mlab appears
        self.assertEqual(response.status_code, 200)

如何修改测试以检查创建的sampleModel对象是否出现在view:page1中?该测试的目的是检查创建的对象是否出现在page1中。

这是我的urls.py

path('<int:pk>/', views.sampleView.as_view(), name='page1'),

1 个答案:

答案 0 :(得分:1)

您可以检查模板中获取的数据是否看起来像这样:

self.assertContains(response, '999999')
self.assertContains(response, 'another field value')

或者直接检查视图本身返回的上下文:

self.assertEqual(response.context['object_name']['field_name'], 'value_of_the_field'))

在这里编辑代码:

def someTest(self):

        # create an object 
        sample = sampleModel.objects.create(unique_id='999999')

        # add code here to pass the sampleModel object created above to view:page1

        # Make sure the sampleModel object created appears in page 1
        response = self.client.get(reverse('view:page1', kwargs={'pk':sample.pk}))  
        # check that above created mlab appears
        self.assertEqual(response.status_code, 200)
        #other stuff to test depending of what your view return.