How to set url link by its name in a template to avoid NoReverseMatch error ?

How to specify url link using name in a template ?
I would like to build main menu on my website and would like to use url names in template pages.

The problem is when I open the page in browser (, I’m getting NoReverseMatch error.

Here is the code I have:

# INDEX.html
<a href="{% url 'index_page' %}">Homepage</a>

# in project folder
urlpatterns = [
    path('test/', include('app_name.urls')),
	# ...

# in app folder
urlpatterns = [
    path('', views.index_page, name='index_page'),
	# ...

def index_page(request):
    products = Product.objects.all()
    context = {'products': products}
    return render(request, 'app_name/INDEX.html', context)

Here is the error when I go to

NoReverseMatch at /test/
Reverse for 'index_page' not found. 'index_page' is not a valid view function or pattern name.

Depending upon the complete contents of your files, you may need to specify the name space in your reference:
<a href="{% url 'app:index_page' %}">Homepage</a>

1 Like

@KenWhitesell thank you. That worked !
Btw, what should I do to avoid using app every time ?
Because in most examples in Django docs, the app part is not added.

Somewhere you have a namespace defined for your application. See the URL namespaces and Namespacing URL names docs for details.

However, I would suggest that having them (namespaces) is a Good Thing™ because it more easily allows you to avoid url-naming conflicts between apps, and, I think it makes it easier to figure out what is being referenced when looking at the code or template.


1 Like