无法在Django中使用反向url函数

问题描述 投票:0回答:1
  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")你有什么主意吗?

django django-rest-framework reverse drf-nested-routers
1个回答
0
投票

self.url = reverse("admins")更改为self.url = reverse("users:admins")如果您设置的网址具有app_name,则查找应具有appname:url namehttps://docs.djangoproject.com/en/3.0/topics/http/urls/

© www.soinside.com 2019 - 2024. All rights reserved.