Django - Reverse for 'index' not found. 'index' is not a valid view function or pattern name
I am new to Django. I have been working based on the template from Mozilla: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website
I have created a project called 'debtSettler'. And it has an app called 'home'.
I have the following url mappings:
./debtSettler/debtSettler/urls.py:
urlpatterns = [
path('home/', include('home.urls')),
path('admin/', admin.site.urls),
path('', RedirectView.as_view(url='home/')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
./debtSettler/home/urls.py:
app_name = 'home'
urlpatterns = [
path('', views.index, name='index'),
path('clubs/', views.ClubListView.as_view(), name='clubs'),
]
And views:
./debtSettler/home/views.py:
from django.http import HttpResponse, HttpResponseRedirect
def index(request):
num_clubs = Club.objects.all().count()
# The 'all()' is implied by default.
num_members = Member.objects.count()
context = {
'num_clubs': num_clubs,
'num_members': num_members,
}
# Render the HTML template index.html with the data in the context variable
return render(request, 'index.html', context=context)
class ClubListView(generic.ListView):
model = Club
def get_context_data(self, **kwargs):
# Call the base implementation first to get the context
context = super(ClubListView, self).get_context_data(**kwargs)
# Create any data and add it to the context
context['some_data'] = 'This is just some data'
return context
In the template, I have two urls that give the error:
<a href=" {% url 'index' %} ">Home</a>
<a href=" {% url 'clubs' %} ">All clubs</a>
Reverse for 'index' not found. 'index' is not a valid view function or pattern name.
If I add the my_app:my_view, it works as expected:
Home All clubs
but I plan to do more of the url mapping further in the app so I want to understand what I am doing wrong with the url. It seems to me like I am doing things very similar to the tutorial.
try to add "home:" before'index'
try this:
<a href=" {% url 'home:index' %} ">Home</a>
<a href=" {% url 'home:clubs' %} ">All clubs</a>
And you should add namespace
urlpatterns = [
path('home/', include('home.urls','home'),namespace = 'home'),
path('admin/', admin.site.urls),
path('', RedirectView.as_view(url='home/')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
You used an app_name
, so then the view names are "namespace" with:
<a href="{% url 'home:index' %}">Home</a>
<a href="{% url 'home:clubs' %}">All clubs</a>