我想从模板文件夹中加载模板,但收到一个错误,说包含的 URLconf 似乎没有任何模式



我正在尝试在我的模板/页面文件夹中加载模板并获取error: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'pages.urls' from 'D:\django\pages\pages\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

我尝试将模板文件夹放在项目和应用程序目录中,但仍然收到相同的错误。

在我的 settings.py 中,我有:

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

和:

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

名为 pages_project 的根项目文件夹中的 urls.py 文件如下所示:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls')),
]

我在名为 Pages 的应用程序文件夹中的 urls.py 如下所示:

from django.urls import path
from . import views
path('', views.HomePageView.as_view(), name='home')

我的 views.py 看起来像:

from django.shortcuts import render
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name= 'home.html'

我在路径 pages/templates/pages/home.html 中有一个名为 home.html 的模板文件,如下所示:

<h1>Homepage</h1>

这与模板没有任何关系。

正如错误所说,包含的 URLconf 中没有任何模式。从主 urls.py 可以看出,您需要定义一个名为urlpatterns的列表,其中包含您的模式。因此,您的页面 urls.py 应该是:

urlpatterns = [
path('', views.HomePageView.as_view(), name='home')
]

最新更新