使用 Django,当我尝试访问应该存在的页面时,为啥找不到 404 错误页面?

Posted

技术标签:

【中文标题】使用 Django,当我尝试访问应该存在的页面时,为啥找不到 404 错误页面?【英文标题】:Using Django, why do I get a 404-error page not found, when I try to acces a page that should exist?使用 Django,当我尝试访问应该存在的页面时,为什么找不到 404 错误页面? 【发布时间】:2021-08-14 18:04:28 【问题描述】:

我创建了一个名为 trydjango 的项目,我可以在其中访问我使用 products/<int:my_id> [name='product'] 链接创建的产品,但不知何故它不起作用,我找不到错误。 当我打开 http://127.0.0.1:8000/products/1/ 时,我得到一个 404 page not found 错误,看起来像这样

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

products/<int:my_id> [name='product']
products/ [name='product-list']
products/<int:my_id>/delete/ [name='product-delete']
about/
[name='home']
contact/
admin/
create/
initial/
The current path, products/1/, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

即使我有一个保存了id=1 的产品。我正在使用我在 URL 中配置的 URL,当我从页面 http://127.0.0.1:8000/products/ 访问它时,我可以看到具有正确 id 的产品存在,在那里我可以看到所有产品的列表及其 id。

这是我的网址:

from django.urls import path

from pages.views import home_view, contact_view, about_view
from products.views import (
    product_list_view,
    product_delete_view,
    product_create_view,
    render_initial_data,
    dynamic_lookup_view,
    )


urlpatterns = [
    path("products/<int:my_id>", dynamic_lookup_view, name='product'),
    path("products/", product_list_view, name="product-list"),
    path("products/<int:my_id>/delete/", product_delete_view, name="product-delete"),
    path("about/", about_view),
    path("", home_view, name="home"),
    path("contact/", contact_view),
    path("admin/", admin.site.urls),
    path("create/", product_create_view),
    path("initial/", render_initial_data),
] 

和我的设置:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$nvha^)-dy*&#_@asdgrh+!63ljr0sl@py8=%z8!si$day)*%z'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'products',
    'pages',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'trydjango.urls'

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': 
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        ,
    ,
]

WSGI_APPLICATION = 'trydjango.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    



# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    ,
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, javascript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

谁能看到我错过了什么?

【问题讨论】:

【参考方案1】:

您的网址格式为:products/&lt;int:my_id&gt;,请求的网址为products/1/。这里有什么区别?那么请求的 url 以 尾随 斜杠 (/) 结尾,而模式则没有。

即使您向products/1 发出请求,您仍然会被重定向到带有斜杠的网址,因为默认情况下,Django 会将不带斜杠的所有网址重定向到附加斜杠的相同网址。因此,只需将模式更改为尾部斜杠即可:

path("products/<int:my_id>/", dynamic_lookup_view, name='product'),

【讨论】:

多么简单的解决方案。非常感谢您的检查!

以上是关于使用 Django,当我尝试访问应该存在的页面时,为啥找不到 404 错误页面?的主要内容,如果未能解决你的问题,请参考以下文章

Django CMS - 创建第一页时模板不存在错误

Django django_admin_log' 不存在

Django - 当页面不存在或用户未通过身份验证时返回更改答案

当我尝试通过 https 登录到 Django 管理员时,python 服务器已关闭且没有任何错误

Django 2.1 令牌匹配查询不存在

存在登录页面时,iOS swift 可访问性应该失败