“反向搜索...未找到”; - 但是还有? [英] "Reverse for ... not found" - but there is?

查看:67
本文介绍了“反向搜索...未找到”; - 但是还有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我已经为此花了30多分钟来敲打我的头,所以这里我处于堆栈溢出状态。

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 %}  

在urls.py中:

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

我仍然得到:
NoReverseMatch at /

Yet I still get: NoReverseMatch at /

未找到 admin的反向字符。 admin不是有效的视图功能或模式名称。

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

为什么?我什至对其进行了测试,并用index替换了admin,并将其重定向到views.index。我尝试用其他所有内容替换模式的名称,并尝试将其与url路径进行匹配(就像现在一样)。没运气!我只是打破了django吗?

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?

推荐答案

如果我们看一下路径,就会看到:

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

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

因此,这意味着 admin 不是路径,而是路径的集合。 admin.site.urls 的后面是一组路径和相应的视图。因此,您不能引用一组URL,只能引用一个路径。

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.

现在在 admin.site.urls <下/ code>,我们看到几个视图:

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')

所以我们可以参考到映射到管理站点(第一个站点)根的管理URL,

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 %}

此处 admin:部分源自管理员应用的命名空间,而:index 部分指代视图。

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

这篇关于“反向搜索...未找到”; - 但是还有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆