LoginSignup
0
0

Djangoでテンプレートを作成する方法

Last updated at Posted at 2023-12-19

Djangoでは好きなようにビューのテンプレートを作成できる。
作り方の簡単なメモ。

テンプレートの作り方

1.urls.pyにパスを追加

urlpatternsに下記部分を追記します。

urls.py
from .views import MyClass #追記

urlpatterns = [
    path('XXXurl/', MyClass.as_view(), #追記
]

2.ビュー用のファイルを作成

下記の通り、ビューファイルを作ってTemplateViewをインポートし、テンプレートとしてhello.htmlを指定します(後ほど作成)。

views.py
from django.views.generic import TemplateView #追記

class MyClass(TemplateView): #追記
    template_name = 'hello.html' #追記

3.テンプレートファイルを作成

まずはプロジェクト直下にtemplatesディレクトリを作成し、その中にhello.htmlという名前のファイルを作ります。

cd /your/project/path
mkdir templates
touch templates/hello.html
hello.html
Hello World!

4.setting.pyを修正

デフォルトだとテンプレートファイルのディレクトリが登録されていないので、下記の通りファイルを修正します。

settings.py
TEMPLATES = [
    'DIRS' = [BASE_DIR / 'templates'], #修正

確認

そして下記を実行すると、ブラウザにhello.htmlの内容が表示されるはずです。

python3 manage.py runserver

image.png

TemplateDoesNotExist エラーの対処方法

テンプレートをいじっていると、おそらく遭遇するであろうエラー。
image.png

「テンプレートが存在しない」と言われているので、下記の点をチェックしましょう。

  • settings.pyのTEMPLATESのDIRSの内容は合っているか
  • ビュー用のファイル名とviews.pyで登録したテンプレート名は一致しているか
  • views.pyで定義したクラス名とurls.pyでインポートしたクラス名は一致しているか

以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0