Django - 帮助! Settings.py、urls.py 和 views.py 导致 404 错误

Django - Help! Settings.py, urls.py and views.py resulting in 404 error

最近我在 运行 我的 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(应用程序)

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 works, but I get the same attribute error above when going to other pages such as http://127.0.0.1:8000/education

更新- 到目前为止,我得到了 'Home' 以外的所有页面。 这是临时修复

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')

那是因为你的家url不匹配。如果您的网站是 localhost:8000,并且您正在访问相同的 url 路径,则将显示 404 未找到,因为您尚未添加主页路径。所以:

app.urls

from django.urls import path
from . import views

urlpatterns = [
    <b>path('', views.index, name="index")</b>, 
    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 函数来呈现某些页面,就像您对其他路由所做的那样。