使用 Django,当我尝试访问应该存在的页面时,为什么会出现 404 错误页面未找到?

时间:2021-05-26 13:24:09

标签: django http-status-code-404

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

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 个答案:

答案 0 :(得分:2)

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

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

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