1

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?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • Does this answer your question? [django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found. 'home' is not a valid view function or pattern name](https://stackoverflow.com/questions/63217879/django-urls-exceptions-noreversematch-reverse-for-home-not-found-home-is-n) – Abdul Aziz Barkat May 26 '22 at 14:40

1 Answers1

1

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thank you! At least now it finds the name, but now it gives the error 'Ad matching query does not exist.'. I substituted the '42' with '1', which is the number of an existing ad page. Do I need to create an ad with another test? – materialAres May 26 '22 at 14:52
  • 1
    @materialAres: you should create a `Ad` first in the test, and then use the primary key of the created `Ad`. – Willem Van Onsem May 26 '22 at 14:58