Django "NoReverseMatch: Reverse for 'ads.views.AdListView' not found" 正在做测试

Django "NoReverseMatch: Reverse for 'ads.views.AdListView' not found" while doing Test

我实施了一些测试来检查某些页面的状态代码,但是这个具有反向功能的测试向我抛出错误:django.urls.exceptions.NoReverseMatch: Reverse for 'ads.views.AdListView' not found . 'ads.views.AdListView' 不是有效的视图函数或模式名称。

阅读 Stack Overflow 上的文档和一些答案我应该在反向函数的括号内使用视图函数名称或模式名称,但其中 none 似乎有效。

这是我的代码:

ads/tests/test_urls.py

from django.test import TestCase
from django.urls import reverse


class SimpleTests(TestCase):
    def test_detail_view_url_by_name(self):
        resp = self.client.get(reverse('ad_detail'))
        # I've also tried: resp = self.client.get(reverse('ads/ad_detail'))
        self.assertEqual(resp.status_code, 200)
...

ads\urls.py

from django.urls import path, reverse_lazy
from . import views


app_name='ads'

urlpatterns = [
    path('', views.AdListView.as_view(), name='all'),
    path('ad/<int:pk>', views.AdDetailView.as_view(), name='ad_detail'),
    ...
    ]

mysite/urls.py

from django.urls import path, include

urlpatterns = [
    path('', include('home.urls')),  # Change to ads.urls
    path('ads/', include('ads.urls')),
    ...
    ]

ads/views.py

class AdDetailView(OwnerDetailView):
    model = Ad
    template_name = 'ads/ad_detail.html'
    
    def get(self, request, pk) :
        retrieved_ad = Ad.objects.get(id=pk)
        comments = Comment.objects.filter(ad=retrieved_ad).order_by('-updated_at')
        comment_form = CommentForm()
        context = { 'ad' : retrieved_ad, 'comments': comments, 'comment_form': comment_form }
        return render(request, self.template_name, context)

知道导致问题的原因吗?

由于您在 urls.py 中使用了 app_name=…,您需要在视图名称中将其指定为命名空间,因此 <b>ads: </b>ad_detail,并指定一个主键:

resp = self.client.get(reverse('<strong>ads:</strong>ad_detail'<strong>, kwargs={'pk': 42}</strong>))

因此我们在这里访问 URL,其中 42 用作 pk URL 参数的值。