質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

Q&A

解決済

1回答

2703閲覧

Djangoチュートリアルで発生するTemplateDoesNotExistエラーについて

yamatan

総合スコア8

Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

0グッド

0クリップ

投稿2022/02/08 04:02

実現したいこと

はじめての Django アプリ作成、その 4で説明されるdetail.htmlの表示を行いたいです。

問題

questionの内容に対して投票するボタンを配置したdetail.htmlをチュートリアルに沿って作成したが以下の
http://127.0.0.1:8000/polls/1/
から、1番目の質問にアクセスしようとすると「TemplateDoesNotExist at /polls/1/」とエラーが表示されます。

エラーの内容を見ると、
C:...\myenv\lib\site-packages\django\template\loader.py
のget_templete関数でdetail.htmlを見つけられないことが原因のようです(myenvは仮想環境です)。
get_tmplete関数呼び出し時のtmplete_name変数には'polls/detail.html'が入っていました。

以下のディレクトリ構造の様にdetail.htmlはpolls/templetes/pollsフォルダに入っていますが、なぜこのエラーが表示されるのでしょうか。わかる方がいましたら、ご教授お願いします。

ディレクトリ構造

myprojectディレクトリのディレクトリツリー(pycacheは省略しています)
C:.
│ db.sqlite3
│ manage.py

├─myproject
│ │ asgi.py
│ │ settings.py
│ │ urls.py
│ │ wsgi.py
│ │ init.py
│ │
│ └─__pycache__


└─polls
│ admin.py
│ apps.py
│ models.py
│ tests.py
│ urls.py
│ views.py
init.py

├─migrations
│ │ 0001_initial.py
│ │ init.py
│ │
│ └─__pycache__


├─templetes
│ └─polls
│ detail.html
│ index.html

└─__pycache__

ソースコード

関係のありそうなコードを貼っておきます。もし不足してる場合は修正依頼をお願いします。

polls/view.py

Python

1from django.shortcuts import render, get_object_or_404 2from .models import Question 3 4 5def index(request): 6 latest_question_list = Question.objects.order_by('-pub_date')[:5] 7 context = {'latest_question_list': latest_question_list} 8 return render(request, 'polls/index.html', context) 9 10def detail(request, question_id): 11 question = get_object_or_404(Question, pk=question_id) 12 return render(request, 'polls/detail.html', {'question': question})

polls/urls.py

Python

1from django.urls import path 2from . import views 3 4app_name = 'polls' 5urlpatterns = [ 6 path('', views.index, name='index'), 7 path('<int:question_id>/', views.detail, name='detail'), 8]

myproject/settings.py

Python

1""" 2Django settings for myproject project. 3 4Generated by 'django-admin startproject' using Django 3.2.12. 5 6For more information on this file, see 7https://docs.djangoproject.com/en/3.2/topics/settings/ 8 9For the full list of settings and their values, see 10https://docs.djangoproject.com/en/3.2/ref/settings/ 11""" 12 13from pathlib import Path 14 15# Build paths inside the project like this: BASE_DIR / 'subdir'. 16BASE_DIR = Path(__file__).resolve().parent.parent 17 18 19# Quick-start development settings - unsuitable for production 20# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 22# SECURITY WARNING: keep the secret key used in production secret! 23SECRET_KEY = 'django-insecure-k$-v3i%5csfkv(oer^f&elgn&!rtuqsi$a%qs0*=#e-%&u#k$g' 24 25# SECURITY WARNING: don't run with debug turned on in production! 26DEBUG = True 27 28ALLOWED_HOSTS = [] 29 30 31# Application definition 32 33INSTALLED_APPS = [ 34 'polls.apps.PollsConfig', 35 'django.contrib.admin', 36 'django.contrib.auth', 37 'django.contrib.contenttypes', 38 'django.contrib.sessions', 39 'django.contrib.messages', 40 'django.contrib.staticfiles', 41] 42 43MIDDLEWARE = [ 44 'django.middleware.security.SecurityMiddleware', 45 'django.contrib.sessions.middleware.SessionMiddleware', 46 'django.middleware.common.CommonMiddleware', 47 'django.middleware.csrf.CsrfViewMiddleware', 48 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 'django.contrib.messages.middleware.MessageMiddleware', 50 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51] 52 53ROOT_URLCONF = 'myproject.urls' 54 55TEMPLATES = [ 56 { 57 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 'DIRS': [], 59 'APP_DIRS': True, 60 'OPTIONS': { 61 'context_processors': [ 62 'django.template.context_processors.debug', 63 'django.template.context_processors.request', 64 'django.contrib.auth.context_processors.auth', 65 'django.contrib.messages.context_processors.messages', 66 ], 67 }, 68 }, 69] 70 71WSGI_APPLICATION = 'myproject.wsgi.application' 72 73 74# Database 75# https://docs.djangoproject.com/en/3.2/ref/settings/#databases 76 77DATABASES = { 78 'default': { 79 'ENGINE': 'django.db.backends.sqlite3', 80 'NAME': BASE_DIR / 'db.sqlite3', 81 } 82} 83 84 85# Password validation 86# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 87 88AUTH_PASSWORD_VALIDATORS = [ 89 { 90 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 }, 92 { 93 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 }, 95 { 96 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 }, 98 { 99 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 }, 101] 102 103 104# Internationalization 105# https://docs.djangoproject.com/en/3.2/topics/i18n/ 106 107LANGUAGE_CODE = 'en-us' 108 109TIME_ZONE = 'UTC' 110 111USE_I18N = True 112 113USE_L10N = True 114 115USE_TZ = True 116 117 118# Static files (CSS, JavaScript, Images) 119# https://docs.djangoproject.com/en/3.2/howto/static-files/ 120 121STATIC_URL = '/static/' 122 123# Default primary key field type 124# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 125 126DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

polls/tmpletes/polls/index.html

html

1{% if latest_question_list %} 2 <ul> 3 {% for question in latest_question_list %} 4 <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> 5 {% endfor %} 6 </ul> 7{% else %} 8 <p>No polls are available.</p> 9{% endif %}

polls/tmpletes/polls/detail.html

html

1<h1>{{ question.question_text }}</h1> 2 3{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} 4 5<form action="{% url 'polls:vote' question.id %}" method="post"> 6{% csrf_token %} 7{% for choice in question.choice_set.all %} 8 <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> 9 <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> 10{% endfor %} 11<input type="submit" value="Vote"> 12</form>

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

デバッグ設定であれば、Templateのローダーが、どのディレクトリを対象にテンプレートを探しているか、エラーメッセージに出力しているはずです。
エラーメッセージを確認してみてください。

投稿2022/02/08 14:11

hasami

総合スコア1277

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yamatan

2022/02/09 07:18

エラーの詳細を確認したところtemplateローダーがpollsアプリフォルダではなく、仮想環境にインストールしたパッケージフォルダ(Libsフォルダ)内を探索していました。setteings.pyファイルのTEMPLATESのDIRをDIRS': ['polls/templates']に変更したところ、TemplateDoesNotExistのエラーが発生しなくなりました。 また、ディレクトリ内のtemplatesがtempl 'e' tesと間違っていたことも原因のようです。 ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問