从urls.py获取路由时出错

时间:2017-09-28 07:27:20

标签: python django django-rest-framework

我正在测试该应用程序。有必要测试处理发送到地址的请求的方法' http://127.0.0.1:8000/api/v1/test/api_address/'。请告诉我,通过reverse()到客户端的完整地址

class MyTestCase(APITestCase):

    def setUp(self):
        self.message = {
            'username': 'user_name',
            'password': 'user_password',
        }

    def test_get_token(self):
        response = self.client.post(reverse('api_address'), self.message)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

urls.py的代码:

users_router = DefaultRouter()
users_router.register(r'test', TestViewSet, 'test')
users_router.register(r'test/api_address', APIAddressRequestSet, 'api_address')

对于当前的实现,反向('地图地址')不起作用,但是出现错误:

django.urls.exceptions.NoReverseMatch: Reverse for 'api_address' not found. 'api_address' is not a valid view function or pattern name.

1 个答案:

答案 0 :(得分:3)

自动生成DefaultRouter的网址名称,请检查the docs

首先设置base_name

# urls.py    
users_router = DefaultRouter()
users_router.register(r'test', TestViewSet, base_name='test')
users_router.register(r'test/api_address', APIAddressRequestSet,
                      base_name='api_address')

现在,您的网址可以通过reverse('test-list') reverse('test-detail')等方式进行反向访问。请查看文档中的表格以了解其他名称。

您的更新测试:

class MyTestCase(APITestCase):

    def setUp(self):
        self.message = {
            'username': 'user_name',
            'password': 'user_password',
        }

    def test_get_token(self):
        # note the appended `-list` to the url name
        response = self.client.post(reverse('api_address-list'), self.message)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)