Django drops ListView and uses DetailView for a list object, then gives NoReverseMatch

Solution for Django drops ListView and uses DetailView for a list object, then gives NoReverseMatch
is Given Below:

PyCharm 2020.2
Python 3.9
Django 3.1
Ubuntu 20.04 LTS

project urls.py:

 urlpatterns = [
    path('', views.home, name="home"),
    path('admin/doc/', include('django.contrib.admindocs.urls')),
    path('admin/', admin.site.urls),
    path('ktab/', include('ktab.urls')),

app.models.py:

 def get_absolute_url(self):
        return django.urls.reverse('EntryDetail_url', kwargs={"slug": self.slug})

app.urls.py:

path('entry/index/', views.EntryIndex.as_view(), name="EntryIndex_url"),
path('entry/list/', views.EntryList.as_view(), name="EntryList_url"),
path('entry/<slug>:<title>/', views.EntryDetail.as_view(),  name="EntryDetail_url"),

app.views.py:

class EntryIndex(ListView):
    model = Entry
    template_name="EntryList_.html"

    def get_context_object_name(self, object_list):
        return 'object'

    def get_queryset(self):
        return Entry.objects.all()

    def get_context_data(self, **kwargs):
        context = super(EntryIndex, self).get_context_data(**kwargs)
        context['searchbox'] = SearchBox()
        return context

class EntryDetail(DetailView):
    model = Entry
    template_name="EntryDetail_.html"

    def get_context_data(self, **kwargs):
        context = super(EntryDetail, self).get_context_data(**kwargs)
        context['searchbox'] = SearchBox()
        return context

class EntryList(ListView):
    model = Entry
    template_name="EntryList_.html"

Error Message:

NoReverseMatch at /ktab/entry/list/
Reverse for 'EntryDetail_url' with keyword arguments '{'slug': 'executive-summary-hattie-urls-and-views'}' not found. 1 pattern(s) tried: ['ktab/entry/(?P<slug>[^/]+):(?P<title>[^/]+)/$']

……

In template /home/malikarumi/Projects/lifeandtimes/chronicle/templates/base_index.html, error at line 0

But of course, there’s nothing there at line zero but the DOCTYPE declaration.

I am trying to call the index for this model’s objects, which is the same as a list. For reasons that I do not understand, and am tired of fighting with, it keeps trying to give me a single object on the detail template. The object ‘executive-summary-hattie-urls-and-views’ happens to be queryset[0].

You can see that I put entry/index and entry/list ahead of entry/ in urls.py, expecting it to latch on to that, which it refuses to do.

I am using class based views. I tried overriding get context name and get queryset, but that has made no difference, either.

In the Traceback, you can see that at first it does get the queryset:

context 
{'entry_list': <QuerySet [<Entry: Executive Summary of "hattie urls and views">, <Entry:....

It has even changed object names as I tried to figure out what it was doing:

object_list': <QuerySet [<Entry: Executive Summary of "hattie urls and views">, <Entry:...

But it always decides to choke on the first one. This is where it changes:

/home/malikarumi/.virtualenvs/chronic_all/lib/python3.9/site-packages/django/template/base.py,

line 858, in _resolve_lookup
                if callable(current):
                    if getattr(current, 'do_not_call_in_templates', False):
                        pass
                    elif getattr(current, 'alters_data', False):
                        current = context.template.engine.string_if_invalid
                    else:
                        try:  # method call (assuming no args required)
                  ----->    current = current() … ←---- 
                        except TypeError:
                            signature = inspect.signature(current)
                            try:
                                signature.bind()
                            except TypeError:  # arguments *were* required
                                current = context.template.engine.string_if_invalid  # invalid method call

Variable    Value
bit     'get_absolute_url'
context 
[{'True': True, 'False': False, 'None': None}, {}, {}, {'paginator': None, 'page_obj': None, 'is_paginated': False, 'object_list': <QuerySet [<Entry: Executive Summary of "hattie urls and views">, <Entry:'...(remaining elements truncated)...']>, 

'view': <ktab.views.EntryList object at 0x7f612c99cb20>}]
current 
<bound method Entry.get_absolute_url of <Entry: Executive Summary of "hattie urls and views">>
self    
<Variable: 'object.get_absolute_url'>
template_name   
'EntryList_.html'

template:

{% for object in object_list %}
    <article class="blogpost">
    <header>
        <h2><a href="{{ object.get_absolute_url }}">{{ object.title }}</a></h2>

The traceback has this line in it 5 times:

/home/malikarumi/.virtualenvs/chronic_all/lib/python3.9/site-packages/django/template/base.py, line 905, in render_annotated
“””
Render the node. If debug is True and an exception occurs during
rendering, the exception is annotated with contextual line information
where it occurred in the template. For internal usage this method is
preferred over using the render method directly.
“””

    try:
---->         return self.render(context) … ←---
        except Exception as e:
            if context.template.engine.debug and not hasattr(e, 'template_debug'):
                e.template_debug = context.render_context.template.get_exception_info(e, self.token)
            raise
    def __iter__(self):

I suppose that’s significant, but I don’t know why it is doing that or how to undo it.

I also tried running the debugger in PyCharm on base.py:

File "/home/malikarumi/.virtualenvs/chronic_all/lib/python3.9/site-packages/django/template/base.py", line 69, in <module>
    from .exceptions import TemplateSyntaxError
ImportError: attempted relative import with no known parent package

This project is about 4 years old, and of course used to work. Now all I can get are the home page and the admin, both of which are on the project urls, not the app. Thanks.

UPDATE 7/31/21:
@ShivendraPratapKushwaha and bdbd: First, thank you both for trying to help me. 2nd, Yes, Shivenra, I noticed that this afternoon when re-reading the docs for the millionth time. I’m sure the changes helped, but it was not a complete solution.

bdbd, as I guess you noticed later, my g.a.u. is already in the first part of my question. Also, I managed to figure out how to make PyCharm’s debugger work. Eventually that led me to realize I had “object.get_absolute_url” in my template when it should have been the url template tag and the named url.

Did you know Django does not inform you of missing or misspelled template variables? Yea, me neither. All PyCharm could tell me was

Exception while resolving variable '%s' in template '%s'.

Is that helpful or what? But it did give me a big hint: The stop and start index of the variable ‘token’. That was enough for me to find object.get_absolute_url and replace it with the url template tag.

Here is something else I learned – I am going into all this detail because it was such a time consuming slog to find this and perhaps it will help others in the near and not so near future. When you click ‘view on site’ from the admin, it uses a view called ‘shortcut’, not your own view code. I got that from the debug toolbar (ddt). So you are not comparing apples to apples when you do that. Then I decided to do something truly radical: I typed in the correct url of a single instance by hand – and it came up! Correctly! Without errors!

This is my current status:

project urls work

There are two models on the app.
If I type in the url to a detail instance on app.Model E, it works.
If I type in the url to a detail instance on app.Model W, it gives me a NoReverseMatch error that does not make a lot of sense because of the arguments it says it got.

If I get to an instance of either app.Model E or app.Model W from the admin, I get a NoReverseMatch error that seems to have the correct arguments, so I am mystified as to why it won’t resolve.

I gave up trying to make the lists work until I get the details working. Going to sleep now…

Based from the errors, the absolute url doesn’t match the definition for EntryDetail_url. So to fix, change the url to properly use the correct kwarg for slug:

path('entry/<slug:slug>/', views.EntryDetail.as_view(),  name="EntryDetail_url"),

And use the correct kwargs in get_absolute_url to match the URL kwarg:

def get_absolute_url(self):
    from django.urls import reverse
    return reverse('EntryDetail_url', kwargs={'slug' : self.slug})

I am trying to call the index for this model’s objects, which is the same as a list. For reasons that I do not understand, and am tired of fighting with, it keeps trying to give me a single object on the detail template. The object ‘executive-summary-hattie-urls-and-views’ happens to be queryset[0].

It gives you the first object, but it fails when it tried to call its get_absolute_url, because of first error caused by mismatch in URL kwargs. If you really want the model objects to call index (although it’s not clear to me why), then you need to change get_absolute_url of Entry to point to the index:

def get_absolute_url(self):
    from django.urls import reverse
    return reverse('EntryIndex_url')

Ok, I have most of this figured out. I bought a bootstrap theme from a designer, and in sprucing up my templates recently I foolishly followed some of his assumptions / suggestions. I also stuck get_absolute_url into the templates because I forgot, and was too lazy, to look up and use the proper url template tag. And I also forgot about the template work I had done when I started getting all these problems, because I thought it had to be ‘code’, not templates or design stuff. The fact that Django doesn’t warn about template errors also didn’t help. But, most of that has been fixed now, and the suggestions the two of you made were helpful. I am still still stuck on the admin link, so I am going to close this question and post a new, more targeted question about that one remaining issue. Thanks!