当我想在单元测试中使用反向功能时,发生django urls.exceptions.NoReverseMatch错误?

我最近开始使用django开发应用程序,this是整个项目的链接。

这是项目结构:

const Button = ({ children,...props }) => (
   <button {...props}>{children}</button>
)

这是文件config/ env/ .env files requirements/ __init__.py ... settings/ __init__.py base.py local.py __init__.py urls.py views.py wsgi.py projects/ api/ town/ apps.py urls.py views.py ... core/ models/ town.py serializers/ town_serializer.py ... tests/ test_town.py manage.py

project/api/town.urls.py

还有from django.urls import path from . import views app_name = 'town' urlpatterns = [ path('town/',views.CreateTownView.as_view(),name='town-list'),path('town/<int:pk>/',views.TownViewSet.as_view(),name='town-detail') ] 的文件:

config/settings/urls.py

]

当我使用以下链接检出from django.contrib import admin from django.urls import path,include # from .views import views urlpatterns = [ path('admin/',admin.site.urls),# path('',views.index) path('api/',include('project.api.city.urls',namespace='city')),path('api/',include('project.api.town.urls',namespace='town')) 时,API可以正常工作,但是当我尝试在pycharm中运行单元测试时,不幸的是发生了一些错误。这是测试模块的一部分,该错误发生在DetaIL_TOWN_URL = reverse('town:town-detail')中:

localhost:8000/api/town

这是错误:

from django.db import IntegrityError
from django.test import TestCase
from project.core.models.town import Town
from django.urls import reverse

from rest_framework.test import APIClient
from rest_framework import status

import unittest

CREATE_TOWN_URL = reverse('town:town-list')
DetaIL_TOWN_URL = reverse('town:town-detail')

显然反向找不到术语raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'town-detail' with no arguments not found. ,但是正如您在town-detail中看到的那样,我已经在项目主URL中将project/api/town.urls.pytown-detail应用URL定义为命名空间{ {1}}。

当我对town进行注释时,我意识到对town的测试将通过,但是当DetaIL_TOWN_URL被定义且未注释时,将发生错误。

那为什么会发生此错误,我该如何解决?

gyglove2008 回答:当我想在单元测试中使用反向功能时,发生django urls.exceptions.NoReverseMatch错误?

URL中的int参数需要镇镇细节。

尝试使用kwargs

reverse('town-detail',kwargs = {'pk':1})

或参数 reverse('town-detail',args = [1]))

有指向文档的链接 https://docs.djangoproject.com/en/2.2/ref/urlresolvers/

本文链接:https://www.f2er.com/3150792.html

大家都在问