【问题标题】:Django - Help! Settings.py, urls.py and views.py resulting in 404 error姜戈——救命! Settings.py、urls.py 和 views.py 导致 404 错误
【发布时间】:2021-11-08 09:23:40
【问题描述】:

最近我在运行 Django 项目时遇到了 404 错误。由于某种原因,我无法弄清楚,我需要帮助。我是 django 和一般编码的新手。它以前工作过,我不知道我做错了什么。 这是错误

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

admin
index.html [name='index']
experience.html [name='experience']
projects.html [name='projects']
research.html [name='research']
education.html [name='education']
404.html [name='comeback']
design.html [name='design']
The empty path didn’t match any of these.

这是程序代码。

这里是views.py

from django.shortcuts import render


def index(request):
    return render(request, 'index.html', {}),

def experience(request):
    return render(request, 'experience.html', {}),

def projects(request):
    return render(request, 'projects.html', {}),

def research(request):
    return render(request, 'research.html', {}),

def education(request):
    return render(request, 'education.html', {}),

def comeback(request):
    return render(request, '404.html', {}),

def design(request):
    return render(request, 'design.html', {}),

这里是 urls.py (app)

from django.urls import path
from . import views



urlpatterns = [
    path('index.html', views.index, name="index"),
    path('experience.html', views.experience, name="experience"),
    path('projects.html', views.projects, name="projects"),
    path('research.html', views.research, name="research"),
    path('education.html', views.education, name="education"),
    path('404.html', views.comeback, name="comeback"),
    path('design.html', views.design, name="design"),
]

这里是 urls.py(设置在哪里)

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

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

这里是settings.py

import os
from pathlib import Path


BASE_DIR = Path(__file__).resolve().parent.parent



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',
    'app',
]

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 = 'portfolio.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'template')],
        '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 = 'portfolio.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/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/3.2/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/3.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static'),
]

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

这是使用时的新错误

path('', views.index, name='index')

复制/粘贴视图出错

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 3.2.7
Python Version: 3.9.1
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'app']
Installed 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']



Traceback (most recent call last):
  File "C:\Users\Trevor\Desktop\django_portfolio\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Trevor\Desktop\django_portfolio\env\lib\site-packages\django\utils\deprecation.py", line 119, in __call__
    response = self.process_response(request, response)
  File "C:\Users\Trevor\Desktop\django_portfolio\env\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response
    if response.get('X-Frame-Options') is not None:

Exception Type: AttributeError at /
Exception Value: 'tuple' object has no attribute 'get'

转到http://127.0.0.1:8000/admin 有效,但在转到http://127.0.0.1:8000/education 等其他页面时出现上述相同的属性错误

更新 - 到目前为止,我得到了除“主页”之外的所有页面。 这是临时修复

urls.ps

from django.urls import path
from . import views


urlpatterns = [
    path('', views.home, name="home"),
    path('experience.html', views.experience, name="experience"),
    path('projects.html', views.projects, name="projects"),
    path('research.html', views.research, name="research"),
    path('education.html', views.education, name="education"),
   
]

这里是views.py

from django.shortcuts import render

# Create your views here.

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


def experience(request):
    return render(request, 'base/experience.html')

def projects(request):
    return render(request, 'base/projects.html')

def research(request):
    return render(request, 'base/research.html')

def education(request):
    return render(request, 'base/education.html')

【问题讨论】:

    标签: python html django django-views django-templates


    【解决方案1】:

    那是因为你的 home url 不匹配。如果您的网站是 localhost:8000,并且您正在访问相同的 url 路径,则会显示 404 not found 因为您没有添加主页路径。所以:

    app.urls

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.index, name="index"), 
        path('experience.html', views.experience, name="experience"),
        path('projects.html', views.projects, name="projects"),
        path('research.html', views.research, name="research"),
        path('education.html', views.education, name="education"),
        path('404.html', views.comeback, name="comeback"),
        path('design.html', views.design, name="design"),
    ]

    你应该在你的视图中有 home 函数来渲染一些页面,就像你对其他路由所做的那样。

    【讨论】:

    • 感谢您的快速回复,至于首页功能,我的首页是index.html。该功能会是什么样子? - 谢谢
    • @TrevorSeibert 已更新。
    • 我删除了 'index.html' 但在运行服务器时出现错误 'tuple' object has no attribute 'get'
    • 我在新错误中编辑为图像并复制/粘贴视图
    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 2020-08-17
    • 2015-07-15
    • 2022-07-06
    • 2013-09-14
    相关资源
    最近更新 更多