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

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

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

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

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

618閲覧

Djangoのフィルター機能の自作がエラーを吐きます。

hokuyan

総合スコア2

Django

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

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

1クリップ

投稿2023/01/30 15:47

前提

pythonのDjangoを用いてWebアプリ構築の勉強をしています。
フィルター機能の自作を行いたいのですが、以下のエラー文が出てしまいます。
TemplateSyntaxError: 'custom_tags' is not a registered tag library.

ディレクトリとファイルの階層は以下のようになっています。

WebAplication └── TemplateExam ├── static ├── TemplateApp | ├── migrations | ├── templatetags | | ├── __pycache__ | | ├── __init__.py | | └── custom_tags.py | ├── __init__.py | ├── admin.py | ├── apps.py | ├── models.py | ├── tests.py | └── views.py ├─ TemplateExam ├─ templates | ├── base.html | ├── home.html | ├── member_detail.html | └── members.html ├─ db.sqlite3 └── manage.py

フィルター機能を使っている箇所

custom_tags.pyで作成したフィルター(calcurate_datetime_to_now)をmember_detail.htmlの10行目で利用しています。

custom_tags.py

python

1from django import template 2from datetime import datetime 3import math 4 5registar = template.Library() 6 7@registar.filter(name='calcurate_datetime_to_now') 8def calcurate_datetime_to_now(value): 9 join_datetime = datetime.strptime(value, ' %Y / %m / %d') 10 now_datetime = datetime.now() 11 # timedelta class 12 diff_datetime = now_datetime - join_datetime 13 diff_days = diff_datetime.days 14 diff_years = math.floor(diff_days / 365) 15 diff_months = math.floor((diff_days - 365 * diff_years) / 30) 16 return f'{diff_years}年 {diff_months}ヶ月'

member_detail.html

html

1{% extends "base.html" %} 2{% block title %}メンバー詳細{{block.super}}{% endblock %} 3{% block content %} 4{% load static %} 5{% load custom_tags %} <!-- 新規追加 --> 6<h1>メンバー詳細画面</h1> 7 <img src="{% static member.picture_path %}"> 8 <p>名前:{{member.name}}</p> 9 <p>入部日:{{member.join_at}}</p> 10 <p>入部から:{{member.join_at|calcurate_datetime_to_now}}</p> <!-- 新規追加 --> 11{% endblock %}

自作したフィルター機能の部分を除いた状態(member_detail.htmlの5,10行目を除いた状態)だと正常に動きます。

エラーはmember_detail.htmlの{% load static %}の部分に問題があると記載されているのですが、原因がつかめません。

エラー全文

Internal Server Error: /app/member/1 Traceback (most recent call last): File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\defaulttags.py", line 1027, in find_library return parser.libraries[name] KeyError: 'custom_tags' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\xxx\OneDrive - maebashi-it.ac.jp\プログラミング\study\study_programing\Python\my_program\django\section5-Template\question116-121\TemplateExa m\TemplateApp\views.py", line 40, in member return render(request, 'member_detail.html', context={ File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\engine.py", line 175, in get_template template, origin = self.find_template(template_name) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\engine.py", line 157, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\loaders\cached.py", line 57, in get_template template = super().get_template(template_name, skip) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\loaders\base.py", line 28, in get_template return Template( File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\base.py", line 154, in __init__ self.nodelist = self.compile_nodelist() File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\base.py", line 200, in compile_nodelist return parser.parse() File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\base.py", line 513, in parse raise self.error(token, e) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\base.py", line 511, in parse compiled_result = compile_func(self, token) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\loader_tags.py", line 293, in do_extends nodelist = parser.parse() File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\base.py", line 513, in parse raise self.error(token, e) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\base.py", line 511, in parse compiled_result = compile_func(self, token) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\loader_tags.py", line 232, in do_block nodelist = parser.parse(("endblock",)) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\base.py", line 513, in parse raise self.error(token, e) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\base.py", line 511, in parse compiled_result = compile_func(self, token) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\defaulttags.py", line 1089, in load lib = find_library(parser, name) File "C:\Users\xxx\xxx\envs\xxx\lib\site-packages\django\template\defaulttags.py", line 1029, in find_library raise TemplateSyntaxError( django.template.exceptions.TemplateSyntaxError: 'custom_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz

ちなみにurls.py、views.py、settings.py、base.htmlはそれぞれ以下のようになっています。

TemplateExam/TemplateExam/urls.py

python

1from django.contrib import admin 2from django.urls import path, include 3 4urlpatterns = [ 5 path("admin/", admin.site.urls), 6 path('app/', include('TemplateApp.urls')), 7]

TemplateExam\TemplateApp\urls.py(ファイルを新規作成)

python

1from django.urls import path 2from . import views 3 4 5app_name = 'app' 6urlpatterns = [ 7 path('home', views.home, name='home'), 8 path('members', views.members, name='members'),#メンバー一覧を表示するURLのパス 9 path('member/<int:id>', views.member, name='member'), #メンバーの詳細画面 10]

TemplateExam\TemplateApp\views.py(追加記入)

python

1# 関数の作成 2 3from django.shortcuts import render 4 5# Create your views here. 6 7#メンバー一覧を表示するための情報 8class Member: 9''' 10join_at:入部した日 11picture_path:画像ファイルのパス 12''' 13 def __init__(self, id, name, join_at, picture_path): 14 self.id = id 15 self.name = name 16 self.join_at = join_at 17 self.picture_path = picture_path 18 19#メンバー一覧を表示するためのリスト 20member_list = [ 21 Member(0,'Taro' ,'2018/04/01' ,'img/taro.jpg' ), 22 Member(1,'Jiro' ,'2019/04/01' ,'img/jiro.jpg' ), 23 Member(2,'Hanako' ,'2019/05/01' ,'img/hanako.jpg' ), 24 Member(3,'Yoshiko' ,'2018/10/01' ,'img/yoshiko.jpg' ), 25] 26 27 28 29#ホーム画面 30def home(request): 31 return render(request, 'home.html') 32 33#メンバー一覧 34def members(request): 35 return render(request, 'members.html', context={ 36 'members':member_list 37 }) 38 39#メンバーの画面詳細 40def member(request, id): 41 return render(request, 'member_detail.html', context={ 42 'member':member_list[id] 43 })

TemplateExam\TemplateExam\settings.py

python

1from pathlib import Path 2import os #--------新規追加 3 4# Build paths inside the project like this: BASE_DIR / 'subdir'. 5BASE_DIR = Path(__file__).resolve().parent.parent 6TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') #----新規追加 7STATIC_DIR = os.path.join(BASE_DIR, 'static') #----新規追加 8 9''' 10省略 11''' 12 13#TEMPLATE_DIRとSTATIC_DIRをそれぞれ指定 14TEMPLATES = [ 15 { 16 "BACKEND": "django.template.backends.django.DjangoTemplates", 17 "DIRS": [TEMPLATE_DIR], #-------新規追加 18 "APP_DIRS": True, 19 "OPTIONS": { 20 "context_processors": [ 21 "django.template.context_processors.debug", 22 "django.template.context_processors.request", 23 "django.contrib.auth.context_processors.auth", 24 "django.contrib.messages.context_processors.messages", 25 ], 26 }, 27 }, 28] 29 30''' 31省略 32''' 33 34#最後尾に新規追加 35STATICFILES_DIRS = [ 36 STATIC_DIR, 37]

同じようなエラーがあるかどうかネットで探してみたのですが、直すべきところがわかりません。
エラーの原因がわかる方いましたらよろしくお願いします。

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

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

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

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

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

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

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

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

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問