【问题标题】:Why console is showing templates not defined error in django为什么控制台在 django 中显示模板未定义错误
【发布时间】:2022-04-20 00:37:45
【问题描述】:

我是 django 新手,我在 django 运行服务器时面临一个问题,我复制并粘贴了我的代码,请告诉我我的代码有什么问题

'DIRS': [templates],
NameError: name 'templates' is not defined

在 settings.py 文件中,我将模板放在 [] 括号中

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [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',
            ],
        },
    },
] 

这是我的观点.py

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

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

这是 urls.py

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('about', views.about, name='about'),
]

【问题讨论】:

    标签: python django


    【解决方案1】:

    模板应该是字符串。所以 ['templates'] 而不是 [templates]

    【讨论】:

      【解决方案2】:

      您需要在此处更改DIRS

      'DIRS': [os.path.join(BASE_DIR, 'templates')],
      

      在这里,Django 期望它有一个模板路径,但你提供了没有任何路径的 templates 变量。

      【讨论】:

        【解决方案3】:

        虽然其他人已经就如何修复它给出了正确的答案,但我想指出一件小事,你得到了NameError,因为你还没有定义名字@ 987654322@。

        NameError 在您使用的变量未在程序中的任何位置定义时引发(如果您在当前范围之外定义它,您将获得UnboundLocalError)。

        如果您将名称模板定义为模板文件夹绝对路径的字符串,这将起作用。不过,永远不要在你的 Django 应用程序中使用绝对路径,因为它会在部署时变得很头疼。

        【讨论】:

          【解决方案4】:

          你必须把你的线路改成这个

          'DIRS': [os.path.join(BASE_DIR, 'templates')],
          

          在设置文件中可以看到BASE_DIR

          BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
          

          将 DIRS 更改为

          'DIRS': [os.path.join(BASE_DIR, 'templates')],
          

          将帮助应用找到模板文件夹。 每个应用程序存储特定应用程序的模板/应用程序名称文件夹中的个人建议。它将帮助您拥有更强大的 Django 应用程序。

          例如,您有投票应用程序,在投票应用程序内部它将是这样的

          pollsApp/templates/pollsApp/index.html 等

          还有here is the official guide, it might help you

          【讨论】:

            猜你喜欢
            • 2012-06-07
            • 2011-05-17
            • 1970-01-01
            • 1970-01-01
            • 2013-08-05
            • 2017-01-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多