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/ '. 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
:
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 .
Set a base_name
first:
# 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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.