【问题标题】:Templatedoesnot exist django模板不存在 django
【发布时间】:2021-08-21 13:29:12
【问题描述】:

在此处输入图像描述我目前正在参加有关 django 的在线课程,并且现在正在处理第 3 部分中的模板,我按照说明进行操作,但每次我去mysite/polls, 我收到“不存在模板”错误。
这是我的投票/view.py。

from django.http import HttpResponse

from .models import Question

from django.shortcuts import render

from django.http import Http404



def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)
def owner(request):
 return HttpResponse("Hello, world. 9d5a197b is the polls index.")

def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

/polls/urls.py


from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
    path('owner', views.owner, name='owner'),

]

mysite/settings.py

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-)_f&roo%#9%s$7&0vjlz@7%k!4q!^jnkc4(vle(xi78u48at@s'

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

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

]

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


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

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

我的 index.html 位于 民意调查/模板/民意调查。 每次我去 python 任何地方显示站点名称/民意调查时, 我得到这个错误。我尝试了很多解决方案, 但我不是 django 专家,所以请帮助我。我还有 5 天的时间提交作业。

/home/1narjess/.virtualenvs/django3/lib/python3.6/site-packages/django/core/handlers/exception.py, line 47, in inner
                response = get_response(request) …
▶ Local vars
/home/1narjess/.virtualenvs/django3/lib/python3.6/site-packages/django/core/handlers/base.py, line 181, in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
/home/1narjess/django_projects/mysite/polls/views.py, line 15, in index
    return render(request, 'polls/index.html', context) …
▶ Local vars
/home/1narjess/.virtualenvs/django3/lib/python3.6/site-packages/django/shortcuts.py, line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using) …
▶ Local vars
/home/1narjess/.virtualenvs/django3/lib/python3.6/site-packages/django/template/loader.py, line 61, in render_to_string
        template = get_template(template_name, using=using) …
▶ Local vars
/home/1narjess/.virtualenvs/django3/lib/python3.6/site-packages/django/template/loader.py, line 19, in get_template
    raise TemplateDoesNotExist(template_name, chain=chain) …
▶ Local vars

enter image description here

【问题讨论】:

    标签: python django templates


    【解决方案1】:

    添加模板 -包含您的HTML页面的目录-DIRS

    看起来像这样:

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

    ]

    【讨论】:

    • @Narjess 好的,请尝试在 INSTALLED_APPS 底部添加您的应用 polls
    • 每次我尝试此操作时都出现问题 :-( 该网站由 PythonAnywhere 托管,这是一个在线托管环境。尝试加载时出现问题;请稍后重试。
    【解决方案2】:

    首先你必须在你的 setting.py 中告诉 django 在你的项目中寻找模板的路径

    在你的 settings.py 中输入路径

    BASE_DIR = Path(__file__).resolve().parent.parent
    TEMPLATES_DIR = BASE_DIR / 'templates'
    

    然后在

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

    在您的模板设置中像这样传递您的模板路径,然后在 manage.py 退出的同一文件夹中创建一个文件夹名称模板并将所有模板复制粘贴到那里 然后你就可以继续下去了 告诉我你是否还有错误

    【讨论】:

    • 我试过了,但我仍然得到同样的错误
    • TemplateDoesNotExist at /polls/polls/index.html
    • django.template.loaders.filesystem.Loader: /home/1narjess/django_projects/mysite/templates/polls/index.html(源不存在)django.template.loaders.app_directories.Loader: /home/1narjess/.virtualenvs/django3/lib/python3.6/site-packages/django/contrib/admin/templates/polls/index.html(源不存在)django.template.loaders.app_directories.Loader:/ home/1narjess/.virtualenvs/django3/lib/python3.6/site-packages/django/contrib/auth/templates/polls/index.html(源不存在)
    • 我没有在本地工作,因为我在任何地方使用 python 来获得我的成绩
    • 添加你的工作目录的截图并添加完整的回溯
    猜你喜欢
    • 2017-01-23
    • 2010-12-27
    • 2021-01-07
    • 2015-12-10
    • 2019-08-08
    • 1970-01-01
    • 2015-07-23
    相关资源
    最近更新 更多