简体   繁体   中英

Django reverse URL for app

I am using a third party app (django-sphinxdoc) in my Django project and I would like to be able to link to it in a base.html template so that it is reachable from all pages that are using base.html, but I just can't figure out how to do this. It works just fine with "Home" and "Admin" as defined below.

I have tried a number of different variants and with the below I get:

Exception Type: NoReverseMatch Exception Value: Reverse for 'doc-list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

I have a urls.py:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^', include('Myapp.urls', namespace='Myapp')),
    url(r'^admin/', admin.site.urls),
    url(r'^docs/', include('sphinxdoc.urls', namespace='Myapp-sphinxdoc'),),
]

A Myapp/urls.py:

from django.conf.urls import include, url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='Myapp-index'),
    url(r'^(?P<detail_id>[0-9]+)/$', views.detail, name='Myapp-detail'),
]

My base.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
    <html lang="en">

<head>
  <title>{% block title %}{% endblock %}</title>
</head>

<body>
  <div class="box">
    <h1>MYAPP</h1>
    <hr>
    <a href="{% url 'Myapp:Myapp-index' %}">Home</a>
    <a href="{% url 'admin:index' %}">Admin</a>
    <a href="{% url 'Myapp-sphinxdoc:doc-list' %}">Docs</a>
    <hr>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
      © Copyright 2017, MG
    {% endblock %}
  </div>
</body>
</html>

In the sphinxdoc urls.py I found the name 'doc-list' which I am trying to refer to above:

urlpatterns = [
    url(r'^$', views.OverviewList.as_view(), name='docs-list',),
...

I guess that I do not understand how to use name and namespace and any suggestions would be much appreciated.

/M

Hmm, now it works, but I do not really understand why... I corrected the typo that was found by nik_m and metmirr and then I added a row to my root urls.py, the third url pattern below:

urlpatterns = [
    url(r'^', include('Myapp.urls', namespace='Myapp')),
    url(r'^admin/', admin.site.urls),
    url(r'^docs/', include('sphinxdoc.urls')),
    url(r'^docs/', include('sphinxdoc.urls', namespace='Myapp-sphinxdoc')),
]

If I remove any of the third or fourth pattern I get errors. So, I am happy that things are working, but I would really like to understand why.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM