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

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

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

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

Q&A

2回答

1045閲覧

【Django】htmlテスト:TemplateDoesNotExist:エラー

a0002

総合スコア7

Django

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

0グッド

0クリップ

投稿2020/07/28 02:32

編集2020/07/29 00:35

前提・実現したいこと

Djangoでpytest(Pythonのテストフレームワーク)を使ってHTMLのテストコードを作成しました。
テスト対象コード(①view.pyと②index.html、urls.py)に対するテストコード(③test_index_html.py)を作成。
③では正しいHTMLが返されることをテストするようなテストコードを作成したが
以下のようなエラーが発生しました。

解決方法をお願いいたします

発生している問題・エラーメッセージ

(trouble1) C:\Users\gdans\Desktop\trouble8_apptest\trouble8\tests>pytest test_index_html.py -v ============================================================================= test session starts ============================================================================== platform win32 -- Python 3.7.7, pytest-5.4.3, py-1.9.0, pluggy-0.13.1 -- c:\users\gdans\anaconda3\envs\trouble1\python.exe cachedir: .pytest_cache rootdir: C:\Users\gdans\Desktop\trouble8_apptest\trouble8\tests plugins: django-3.9.0 collected 1 item test_index_html.py::HtmlTests::test_html FAILED [100%] =================================================================================== FAILURES =================================================================================== _____________________________________________________________________________ HtmlTests.test_html ______________________________________________________________________________ self = <trouble8.tests.test_index_html.HtmlTests testMethod=test_html>, result = None def test_html(self, result=None): request = HttpRequest() response = index(request) > expected_html = render_to_string('trouble8/index.html' ,{'data': []}) test_index_html.py:18: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ........\anaconda3\envs\trouble1\lib\site-packages\django\template\loader.py:61: in render_to_string template = get_template(template_name, using=using) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ template_name = 'trouble8/index.html', using = None def get_template(template_name, using=None): """ Load and return a template for the given name. Raise TemplateDoesNotExist if no such template exists. """ chain = [] engines = _engine_list(using) for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) > raise TemplateDoesNotExist(template_name, chain=chain) E django.template.exceptions.TemplateDoesNotExist: trouble8/index.html ........\anaconda3\envs\trouble1\lib\site-packages\django\template\loader.py:19: TemplateDoesNotExist ---------------------------------------------------------------------------- Captured stderr setup ----------------------------------------------------------------------------- Creating test database for alias 'default'... --------------------------------------------------------------------------- Captured stderr teardown --------------------------------------------------------------------------- Destroying test database for alias 'default'... =========================================================================== short test summary info ============================================================================ FAILED test_index_html.py::HtmlTests::test_html - django.template.exceptions.TemplateDoesNotExist: trouble8/index.html ============================================================================== 1 failed in 0.89s ===============================================================================

ディレクトリの構成

├─trouble8 │ │ admin.py │ │ apps.py │ │ calc.py │ │ find.py │ │ forms.py │ │ json.py │ │ login.py │ │ models.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├─migrations │ │ │ 0001_initial.py │ │ │ __init__.py │ │ │ │ │ └─__pycache__ │ │ 0001_initial.cpython-37.pyc │ │ __init__.cpython-37.pyc │ │ │ ├─templates │ │ │ 403.html │ │ │ 404.html │ │ │ 500.html │ │ │ aaa.html │ │ │ base.html │ │ │ delete.html │ │ │ edit.html │ │ │ find.html │ │ │ index.html │ │ │ json.html │ │ │ read.html │ │ │ result.html │ │ │ signup.html │ │ │ │ │ └─registration │ │ login.html │ │ logout.html │ │ │ ├─tests │ │ │ test_index_html.py │ │ │ __init__.py │ │ │ │ │ ├─.pytest_cache │ │ │ │ │ └─__pycache__ │ │ │ └─__pycache__ │ ├─trouble8_app │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └─__pycache__ │ └─__pycache__ test_1-2-2.cpython-37-pytest-5.4.3.pyc

該当のソースコード

◆①テスト対象コード:view.py

from django.shortcuts import render from .models import UnitInfo def index(request, num = 1): data= UnitInfo.objects.all() params={ 'title':'(Index)', 'data': data, } return render(request, 'index.html', params)

◆②テスト対象コード:index.html

{% extends "base.html" %} {% block content %} <h4>{{title}}</h4> <table class="table table-striped table-bordered"> <thead> <tr> <th scope="col">ID</th> <th scope="col">シリーズ</th>  </tr> </thead> <tbody> {% for item in data %} <tr> <td>{{item.id}}</td> <td>{{item.Sname2}}</td> </tr> {% endfor %} </tbody> </table> {% endblock content %}

◆テスト対象コード:urls.py

from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:num>', views.index, name='index'), ]

◆③テストコード:test_index_html.py

import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'trouble8_app.settings') import django django.setup() from django.http import HttpRequest from django.template.loader import render_to_string from django.test import TestCase from trouble8.views import index import pytest @pytest.mark.django_db class HtmlTests(TestCase): def test_html(self, result=None): request = HttpRequest() response = index(request) expected_html = render_to_string('trouble8/index.html' ,{'data': []}) assert response.content.decode() == expected_html

試したこと

エラーに「emplateDoesNotExist」と書かれているので
settingsファイルに以下を◆#追記◆したがエラー内容は変わらなかった

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

補足情報(FW/ツールのバージョンなど)

Python 3
anaconda3

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

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

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

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

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

mtb_beta

2020/07/28 16:51

とりあえず、ログやコードが見にくいので、バッククォートで囲って欲しいです。例 ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['trouble8/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', ], }, }, ] ```
a0002

2020/07/29 00:37

ご指摘をありがとうございます まだ使い始めたばかりなので、今後もご指摘のほどよろしくお願いいたします。
guest

回答2

0

ご連絡をありがとうございます

pytestは以下のコマンドで以前インストールいたしました

pip install pytest-django

1から4を試してみると、前回同様のTemplateDoesNotExistエラーが発生していました

(trouble1) C:\Users\gdans\Desktop\trouble8_apptest>pytest ==================================================================================== test session starts ===================================================================================== platform win32 -- Python 3.7.7, pytest-5.4.3, py-1.9.0, pluggy-0.13.1 django: settings: trouble8_app.settings (from ini) rootdir: C:\Users\gdans\Desktop\trouble8_apptest, inifile: pytest.ini plugins: django-3.9.0 collected 1 item trouble8\tests\test_index_html.py F [100%] ========================================================================================== FAILURES ========================================================================================== ____________________________________________________________________________________ HtmlTests.test_html _____________________________________________________________________________________ self = <trouble8.tests.test_index_html.HtmlTests testMethod=test_html>, result = None def test_html(self, result=None): request = HttpRequest() response = index(request) > expected_html = render_to_string('trouble8/index.html' ,{'data': []}) trouble8\tests\test_index_html.py:18: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ....\anaconda3\envs\trouble1\lib\site-packages\django\template\loader.py:61: in render_to_string template = get_template(template_name, using=using) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ template_name = 'trouble8/index.html', using = None def get_template(template_name, using=None): """ Load and return a template for the given name. Raise TemplateDoesNotExist if no such template exists. """ chain = [] engines = _engine_list(using) for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) > raise TemplateDoesNotExist(template_name, chain=chain) E django.template.exceptions.TemplateDoesNotExist: trouble8/index.html ....\anaconda3\envs\trouble1\lib\site-packages\django\template\loader.py:19: TemplateDoesNotExist ================================================================================== short test summary info =================================================================================== FAILED trouble8/tests/test_index_html.py::HtmlTests::test_html - django.template.exceptions.TemplateDoesNotExist: trouble8/index.html ===================================================================================== 1 failed in 0.56s ======================================================================================

投稿2020/07/30 06:39

a0002

総合スコア7

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

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

0

@pytest.mark.django_db を書いているということは、pytest-djangoはインストールされていますか?

インストールされている場合、次の1から4を試すとどうでしょうか?

1 trouble8_app/settings.py に以下を書く。(importとBASE_DIRがある場合は省略で)

python

1import os 2BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 3 4TEMPLATES = [ 5 { 6 'BACKEND': 'django.template.backends.django.DjangoTemplates', 7 'DIRS': [os.path.join(BASE_DIR, 'templates')], 8 'APP_DIRS': True, 9 'OPTIONS': { 10 'context_processors': [ 11 'django.template.context_processors.debug', 12 'django.template.context_processors.request', 13 'django.contrib.auth.context_processors.auth', 14 'django.contrib.messages.context_processors.messages', 15 ], 16 }, 17 }, 18]

2 test_index_html.py から次の行を消す

python

1import os 2os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'trouble8_app.settings') 3import django 4django.setup()

3 pytest.ini を追加する

場所は C:\Users\gdans\Desktop\trouble8_app\pytest.ini

中身は以下。

[pytest] DJANGO_SETTINGS_MODULE = trouble8_app.settings

4 Djangoプロジェクトのルートでpytest を実行する

cd C:\Users\gdans\Desktop\trouble8_app pytest

投稿2020/07/28 16:56

編集2020/07/29 11:18
mtb_beta

総合スコア181

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

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

a0002

2020/07/29 00:38

ご連絡をありがとうございます。 こちらも早速ディレクトリの構成を追加してみました。
a0002

2020/07/31 06:35 編集

ご連絡をありがとうございます pytestは以下のコマンドで以前インストールいたしました > pip install pytest-django
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問