不能在 Django 中使用反向 url 函数

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)),
]

当我运行python .\manage.py test apps.users.tests 出现此错误

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 folders 我想知道为什么不能得到 reverse("admins") 你有什么想法吗?

根据 the documentation,如果要访问列表视图,url 的名称应为 admins-listregister 函数的参数名称也可以是 basename 而不是 base_name.