Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Reverse for ... not found" - but there is?

Ok, I've been banging my head against this for 30+ minutes, so here I am on stack overflow.

I've got in a template:

{% if user.is_authenticated %}
<a href="{% url 'admin' %}">                                
   Admin
</a>  
{% endif %}  

And in urls.py:

urlpatterns = [
  path('admin', admin.site.urls, name = 'admin'),  
  path('', views.index, name ='index'), 
]

Yet I still get: NoReverseMatch at /

Reverse for 'admin' not found. 'admin' is not a valid view function or pattern name.

Why is that? I even tested it out, and replaced admin with index, and it redirects me to views.index. I tried replacing the name of the pattern with everything else and tried matching it with the url path as well (like it is now). No luck! Did I just break django?

like image 448
KayleMaster Avatar asked Oct 28 '18 18:10

KayleMaster


1 Answers

If we take a look at the path, we see:

path('admin', admin.site.urls, name='admin'),

This thus means that admin is not a path, it is a collection of paths. Behind the admin.site.urls there is a set of paths and corresponding views. So you can not refer to a group of URLs, you can only refer to a single path.

Now under the admin.site.urls, we see several views:

>>> admin.site.urls
([<URLPattern '' [name='index']>,
  <URLPattern 'login/' [name='login']>,
  <URLPattern 'logout/' [name='logout']>,
  <URLPattern 'password_change/' [name='password_change']>,
  <URLPattern 'password_change/done/' [name='password_change_done']>,
  <URLPattern 'jsi18n/' [name='jsi18n']>,
  <URLPattern 'r/<int:content_type_id>/<path:object_id>/' [name='view_on_site']>,
  <URLResolver <URLPattern list> (None:None) 'auth/group/'>,
  <URLResolver <URLPattern list> (None:None) 'auth/user/'>,
  <URLPattern '^(?P<app_label>auth)/$' [name='app_list']>],
 'admin',
 'admin')

So we can refer to the admin URL that maps to the "root" of the admin site (the first one), with:

{% if user.is_authenticated %}
<a href="{% url 'admin:index' %}">
   Admin
</a>
{% endif %}

Here the admin: part originates from the namespace of the admin "app", and the :index part refers to the name of the view.

like image 146
Willem Van Onsem Avatar answered Oct 24 '22 06:10

Willem Van Onsem