简体   繁体   English

为什么我在 Django 的 URL 模式中收到“找不到页面”错误?

[英]Why am I getting a 'Page Not Found' error in Django's URL patterns?

I'm new to Django and I'm just trying to create a small application to output 'Hello World'.我是 Django 的新手,我只是想创建一个小应用程序来输出“Hello World”。 When I run my code, it says 'Page not found' and gives me the following reason:当我运行我的代码时,它显示“找不到页面”并给出以下原因:

'Using the URLconf defined in helloworld_project.urls, Django tried these URL patterns, in this order: '使用 helloworld_project.urls 中定义的 URLconf,Django 按以下顺序尝试了这些 URL 模式:

admin/行政/

home/家/

The empty path didn't match any of these.'空路径与这些都不匹配。

I'm a bit confused as to why this is happening.我有点困惑为什么会这样。 I've included a few samples of my code.我已经包含了我的代码的一些示例。 Any assistance would be greatly appreciated!任何帮助将不胜感激!

urls.py网址.py

from django.contrib import admin
from django.urls import path
from my_app.views import HomeView
urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', HomeView.as_view())
]

views.py视图.py

from __future__ import unicode_literals
from django.shortcuts import render
from django.views.generic import TemplateView
class HomeView(TemplateView):
    template_name = 'index.html'

index.html索引.html

<html>
<head><title>Home Page</title></head>
<body>
Hello world
</body>
</html>

If you're running Django in the port for example 8000, the url:如果您在端口(例如 8000)中运行 Django,则 url:

localhost:8000/

is the empty pattern url.是空模式网址。

according to your URLs definitions you've to:根据您的 URL 定义,您必须:

localhost:8000/home/

or change your url to:或将您的网址更改为:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('^$', HomeView.as_view())    # Point the empty pattern to your view.
]

You need to change your url like:您需要更改您的网址,例如:

urlpatterns = [
    path('', someview), 
    path('admin/', include(admin.site.urls) ),
    path('home/', HomeView.as_view(), name='somename')
]

The error is obtained because when you run your project, it looks for an empty url like localhost:8000/ instead of localhost:8000/home/ .之所以会出现该错误,是因为当您运行项目时,它会查找一个空 url,如localhost:8000/而不是localhost:8000/home/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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