2
  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.

我的结构文件夹像这样我的文件夹 我想知道为什么不能得到reverse("admins") 你知道吗?

4

1 回答 1

1

根据文档,如果要访问列表视图,则 url 的名称应为admins-list. 您的函数的参数名称register也可能basename不是base_name.

于 2020-01-02T11:25:10.890 回答