简体   繁体   English

从urls.py获取路线时出错

[英]Error getting route from urls.py

I'm testing the application. 我正在测试应用程序。 It is necessary to test the method of processing requests coming to the address ' http://127.0.0.1:8000/api/v1/test/api_address/ '. 有必要测试处理请求到地址“ http://127.0.0.1:8000/api/v1/test/api_address/ ”的方法。 Tell me, please, as through reverse () the full address to the client 请告诉我,如通过反向()将完整地址发送给客户

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)

Code for urls.py : urls.py代码:

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

with the current implementation, reverse ('map address') does not work, falling with an error: 在当前的实现中,反向(“映射地址”)不起作用,并出现错误:

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

The url names for DefaultRouter are automatically generated, check the docs . DefaultRouter的网址名称是自动生成的,请检查docs

Set a base_name first: 首先设置一个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')

Now your urls are reverse-accessible via reverse('test-list') reverse('test-detail') , etc. Check the table in the docs for the other names. 现在,您可以通过reverse('test-list') reverse('test-detail')等反向访问url。请检查文档中的其他名称表。

Your updated test: 您更新的测试:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM