1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

コピペで出来るDjangoアプリケーション開発環境構築(その3)

Posted at

はじめに

この講座を見てDjangoの勉強をしています。
今後の開発のために簡潔に開発の流れをまとめました。

その3です。
ここではtemplatesフォルダの移動の仕方を学びます。

その1
その2

開発環境構築の流れ(続き)

templatesフォルダを移動する

外側のsample_project内にtemplatesフォルダを作成する

さらにtemplatesフォルダ内にさらにindex.htmlを追加する

index.html
<h1>移動できた</h1>

settings.pyを修正する

先ほど作成したtemplatesフォルダ内を参照するようにしていきます。

14行目くらい

from pathlib import Path
+ import os

↑下の記述に必要

17行目くらい

BASE_DIR = Path(__file__).resolve().parent.parent
+ TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

イメージは下のような式と同じ。

TEMPLATE_DIR = "BASE_DIR/templates"

BASE_DIR内のtemplatesフォルダをデフォルトで認識してくれるようにしたい。
その設定に用いるパラメータTEMPLATE_DIRを設定した。

そして下の変更で実際に設定する。

59行目くらい

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

views.pyを修正する

def index(request):
-   return render(request, 'appapp/index.html')
+   return render(request, 'index.html')

自動でtemplatesフォルダを見てくれるようになっているので、templates/index.htmlなどとしない。

実行確認

$ python manage.py runserver

urlの末尾にsample_appと追加して実行。「移動できた」と表示されればおk

今後のために少し変更

templatesフォルダの直下にindex.htmlファイルを置いていたが、もう1階層下げる。

template_appフォルダを作成し、その中にindex.htmlを移動する

views.pyを修正する

def index(request):
-   return render(request, 'index.html')
+   return render(request, 'template_app/index.html')

実行確認

$ python manage.py runserver

urlの末尾にsample_appと追加して実行。「移動できた」と表示されればおk

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?