找不到路

时间:2019-06-28 23:07:33

标签: python django

我的代码有问题,我试图在应用程序内创建一个新的URL文件,并在主URL文件中放入函数include,但运行代码时出现错误,这是我的代码

错误消息:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/index
Using the URLconf defined in f_project.urls, Django tried these URL patterns, in this order:

admin/
^$
^first_app/
The current path, index, didn't match any of these.

f_project.urls的代码

from django.contrib import admin
from django.urls import path, include
from first_app import views, urls



urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'^$', views.index),
    path(r'^first_app/', include('first_app.urls')),
]

first_app.urls的代码

from django.urls import path
from first_app import views

urlpatterns = [
    path(r'^$', views.index, name='index'),
]

请有人帮我解决

1 个答案:

答案 0 :(得分:0)

您正在尝试访问index/网址,但未在任何url文件中设置该模式。

如果要设置该网址格式,则必须这样做:

from django.contrib import admin
from django.urls import path, include
from first_app import views, urls



urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'^index/', views.index),
    path(r'^first_app/', include('first_app.urls')),
]

您还将包括另一个urls文件,但它引用相同的视图。无论如何,如果您在first_app urls.py中设置了index/网址格式,如下所示:

from django.urls import path
from first_app import views

urlpatterns = [
    path(r'^index/', views.index, name='index'),
]

该模式的正确网址为first_app/index/

在两个url文件中,您要寻址同一视图(first_app.views.index),因此两个url(index/first_app/index/)都将完全相同。