Search code examples
djangodjango-rest-frameworkreversedrf-nested-routers

can't use reverse url function in django


  1. tests.py
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from .models import User

class UserCreateAPIViewTestCase(APITestCase):

    def setUp(self):
        super().setUp()
        self.url = reverse("admins")

    def test_user_creating(self):
        user_data = {}
        response = self.client.post(self.url, user_data, format="json")
        self.assertEqual(response.status_code,
                         status.HTTP_403_FORBIDDEN)

2.urls.py

from django.urls import path
from django.conf.urls import include
from rest_framework_nested.routers import SimpleRouter
from apps.users.views import (
    CreateProviderViewSet,
    LoginViewSet,
    UserViewSet,
    ProviderViewSet,
    ClientViewSet,
    LoginAsViewSet
)

app_name = 'users'

router = SimpleRouter(trailing_slash=False)
router.register("admins", UserViewSet, base_name='admins')
router.register("providers", ProviderViewSet, base_name='providers')
router.register("clients", ClientViewSet, base_name='clients')
router.register("login", LoginViewSet, base_name='auth')
router.register("login-as", LoginAsViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

when I run python .\manage.py test apps.users.tests This error occurs

ERROR: test_user_creating (apps.users.tests.UserCreateAPIViewTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\vu.tran\Desktop\kona-server\apps\users\tests.py", line 19, in setUp
    self.url = reverse("admins")
  File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\urls\base.py", line 90, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\urls\resolvers.py", line 668, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'admins' not found. 'admins' is not a valid view function or pattern name.

my structure folders like this my folders I wonder why cannot get reverse("admins") Do you have any idea?


Solution

  • According to the documentation, if you want to access the list view, the name for the url should be admins-list. The name of the argument for your register function may also be basename instead of base_name.