【问题标题】:Getting error TemplateDoesNotExist at / when loading home page template - Django + Bulma, Sass加载主页模板时/时出现错误 TemplateDoesNotExist - Django + Bulma,Sass
【发布时间】:2020-03-02 01:50:42
【问题描述】:

我是 Django 初学者,一直在尝试许多解决方案,但都没有成功。尝试在 Django 站点中使用 Sass 自定义 Bulma 框架。我认为这与我的项目目录结构有关,而且我一直在搞乱它,所以肯定有我没有看到的东西。

我确定我有多个不需要的文件,但不确定要删除哪些文件以及保留或移动哪些文件。



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

Django Version: 3.0.3
Python Version: 3.8.2
Installed Applications:
['serappis.apps.SerappisConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django_simple_bulma',
 'sass_processor']
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',
 'whitenoise.middleware.WhiteNoiseMiddleware']

Template loader postmortem
Django tried loading these templates, in this order:

Using engine django:
    * django.template.loaders.filesystem.Loader: /Users/molly/Documents/Dev Projects/SerapisDjango/serapissite/templates/index.html (Source does not exist)
    * django.template.loaders.filesystem.Loader: /Users/molly/Documents/Dev Projects/SerapisDjango/serapissite/templates/index.html (Source does not exist)
    * django.template.loaders.app_directories.Loader: /Users/molly/Documents/Dev Projects/SerapisDjango/serapissite/serappis/templates/index.html (Source does not exist)
    * django.template.loaders.app_directories.Loader: /Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/contrib/admin/templates/index.html (Source does not exist)
    * django.template.loaders.app_directories.Loader: /Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/contrib/auth/templates/index.html (Source does not exist)



Traceback (most recent call last):
  File "/Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/molly/Documents/Dev Projects/SerapisDjango/serapissite/serappis/views.py", line 7, in index
    return render(request, 'index.html')
  File "/Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/template/loader.py", line 61, in render_to_string
    template = get_template(template_name, using=using)
  File "/Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/template/loader.py", line 19, in get_template
    raise TemplateDoesNotExist(template_name, chain=chain)

Exception Type: TemplateDoesNotExist at /
Exception Value: index.html
serapissite
|-- node_modules
|-- serapissite
|   `-- settings
|       `-- __init__.py
|-- db.sqlite3
|-- manage.py
|-- package-lock.json
|-- package.json
|-- urls.py
|-- serappis
|   |-- static
|   |   |-- css
|   |   |   `-- mystyles.css
|   |   |-- node_modules
|   |   |-- sass
|   |   |   `-- mystyles.scss
|   |   `-- package-lock.json
|   |-- templates
|   |   `-- serappis
|   |       `-- index.html
|   |-- urls.py
|   `-- views.py
`-- templates
    `-- serapissite
        `-- index.html

编辑:在此处添加 /serapissite/settings/init.py 代码

"""
Django settings for serapissite project.

Generated by 'django-admin startproject' using Django 3.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os
import django
from django.conf import settings

PROJECT_DIR = os.path.dirname(__file__)

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

TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#c6!@3j8zphb3k4rx9mollyl%ep4rvvx42!@3v'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'serappis.apps.SerappisConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_simple_bulma',
    'sass_processor',
]

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',
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

ROOT_URLCONF = 'serapissite.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 = 'serapissite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.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/3.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/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Chicago'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

STATIC_ROOT = '/serapissite/serappis/static/'

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'sass_processor.finders.CssFinder',
    'django.contrib.staticfiles.finders.FileSystemFinder',
]

STATICFILE_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

# Django Sass
SASS_PROCESSOR_ROOT = os.path.join(BASE_DIR, 'static')

编辑:serapissite/serappis/urls.py 代码在这里

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

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

/serapissite/serappis/views.py 代码在这里:

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader


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

编辑:我想通了!我进行了另一次完全重建,并更清楚地命名了我的目录,同时最大限度地减少了包/额外应用程序的数量。

【问题讨论】:

  • 请显示 urls.py、与模板相关的设置以及尝试呈现此模板的视图。
  • render 调用更改为:return render(request, 'serapissite/index.html'),但也将更改保留为settings.py,我在下面提出了建议。

标签: python django templates sass bulma


【解决方案1】:

您似乎选择了全局模板目录(而不是每个应用的模板目录)。没有错,但 Django 默认不看那里。

您需要在您的settings.py 中添加一些类似的内容:

TEMPLATES = [
    {
        ...
        'DIRS': [
            os.path.join(BASE_DIR, '..', 'templates')
        ],
        ...
    },
]

这将告诉 Django 查看您的任何应用之外的 templates 文件夹。

注意:根据您使用的 Django 版本,您可能需要调整传递给 os.path.join 的参数以指向您的 templates 文件夹。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 2016-05-06
    • 2017-09-05
    相关资源
    最近更新 更多