Skip to content
Advertisement

Reverse for ‘topic’ not found. ‘topic’ is not a valid view function or pattern name (another one)

I’m aware that there are quite a few similar posts like this one, but I still can’t figure it out. This is the code in the ‘topics’ template that links each individual ‘topic’ to it (also the code causing the error):

<a href = "{% url 'topic' topic.id %}">{{ topic }}</a>

Error being:

django.urls.exceptions.NoReverseMatch: Reverse for 'topic' not found. 'topic' is not a valid view function or pattern name.

Here is urls.py:

urlpatterns=[
    #your paths go here
    path('', views.index, name='index'), # home page
    path('topics/', views.topics, name='topics'),
    path('topics/<int:topic_id>/', views.topics, name='topics') # add id arguemnt since each entry is linked to topic by id
]

Here is the topic function in views.py:

def topic(request):
    topic = Topic.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('-date_added') # minus sign indicates reverse order
    context = {'topic':topic, 'entries':entries}
    return render(request, 'learning_logs/topic.html', context)

Advertisement

Answer

Look at second path – you need name topic, not topics

    path('topics/', views.topics, name='topics'), 
    path('topics/<int:topic_id>/', views.topic, name='topic') <<<---THIS

And in views maybe with topic_id:

def topic(request, topic_id):
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement