尝试单击按钮以重定向到getonboard.html时,出现以下错误:
django.urls.exceptions.NoReverseMatch: Reverse for 'getonboard' not found. 'getonboard' is not a valid view function or pattern name.
artdb / urls.py:
path('getonboard/',views.getonboard,name='getonboard'),
templates / artdb / base.html:
<p><a class="btn btn-primary btn-lg" href="{% url 'getonboard' %}" role="button">Get onboard »</a></p>
artdb / views.py:
def getonboard(request):
return render(request,'artdb/getonboard.html')
templates / artdb / getonboard.html:
{% extends "artdb/base.html" %}
{% block content %}
<h2>getonboard template</h2>
<p>this is the getonboard text</p>
{% endblock content %}
完整的主要urls.py:
"""winmalist URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('artdb/', include('artdb.urls')),
path('admin/', admin.site.urls),
]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
完整的artdb / urls.py:
from django.urls import path
from django.views.generic import TemplateView
from artdb.views import PersonList
from . import views
app_name='artdb'
urlpatterns = [
# path('base/',views.base,name='base.html'),
path('getonboard/',views.getonboard,name='getonboard'),
path('index/',views.index,name='index'),
path('persons/',PersonList.as_view()),
path('',TemplateView.as_view(template_name='artdb/base.html')),
path('test2',TemplateView.as_view(template_name='artdb/test2.html')),
# path('', views.IndexView.as_view(), name='index'),
# path('contract', views.contract, name='contract'),
# path('<int:person_id>/test1/', views.test1, name='test1'),
]
有什么想法吗?
答案 0 :(得分:2)
当您包含其他应用程序中的urlpatterns时,通常会通过在应用程序内部的urls.py文件中添加app_name = 'artdb'
行来为这些URL命名空间。因此,如果主urls.py文件包含以下行:
urlpatterns = [
path('artdb/', include('artdb.urls')),
...]
artdb / urls.py文件包含以下几行:
app_name = 'artdb'
urlpatterns = [
path('getonboard/', views.getonboard, name='getonboard'),
...]
然后您可以通过对名称空间进行命名来反转此URL:
reverse('artdb:getonboard')
这使您可以在多个应用程序中使用相同的名称(例如,index
是常见的),例如artdb:index
和user:index
。