Home > OS >  Django "NoReverseMatch: Reverse for 'ads.views.AdListView' not found" while doin
Django "NoReverseMatch: Reverse for 'ads.views.AdListView' not found" while doin

Time:05-27

I implemented some tests to check the status code of some pages, but this one with the reverse function throws me the error: django.urls.exceptions.NoReverseMatch: Reverse for 'ads.views.AdListView' not found. 'ads.views.AdListView' is not a valid view function or pattern name.

Reading the documentation and some answers on Stack Overflow I'm supposed to use either the view function name or the pattern name inside the parenthesis of the reverse function, but none of them seems to work.

Here's my code:

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)

Any idea of what is causing the problem?

CodePudding user response:

Since you use an app_name=… in your urls.py, you need to specify this as a namespace in the name of the view, so ads:ad_detail, and specify a primary key:

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

So here we visit the URL where 42 is used as value for the pk URL parameter.

  • Related