首页 > 解决方案 > 为什么我可以访问同一目录中的主页时无法访问关于页面?

问题描述

我可以访问 home.html ( http://127.0.0.1:8000/ ) 没有任何问题,但关于页面 ( http://127.0.0.1:8000/about/ ) 给我以下错误:

Using the URLconf defined in django_project.urls, Django tried these URL patterns, in this order:

admin/
[name='blog-home']
about [name='blog-about']
The current path, about/, didn't match any of these.

django 项目文件夹 urls.py:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]

应用程序文件夹 urls.py:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='blog-home'),
    path('about', views.about, name='blog-about'),
]

应用文件夹views.py:

from django.shortcuts import render

def home(request):
    return render(request, 'blog/home.html')


def about(request):
    return render(request, 'blog/about.html')

目录结构:

.
├── blog
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       └── __init__.cpython-37.pyc
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-37.pyc
│   │   ├── apps.cpython-37.pyc
│   │   ├── __init__.cpython-37.pyc
│   │   ├── models.cpython-37.pyc
│   │   ├── urls.cpython-37.pyc
│   │   └── views.cpython-37.pyc
│   ├── static
│   │   └── blog
│   │       ├── css
│   │       │   ├── main.css
│   │       │   └── test.css
│   │       ├── images
│   │       │   ├── favicon.png
│   │       │   └── freedom.jpg
│   │       └── js
│   ├── templates
│   │   └── blog
│   │       ├── about.html
│   │       ├── home.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── db.sqlite3
├── django_project
│   ├── asgi.py
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-37.pyc
│   │   ├── settings.cpython-37.pyc
│   │   ├── urls.cpython-37.pyc
│   │   └── wsgi.cpython-37.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

12 directories, 36 files

标签: djangopycharm

解决方案


你必须在 urls.py 中为你的路径 url 添加一个斜杠:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='blog-home'),
    path('about/', views.about, name='blog-about'),
]

推荐阅读