LoginSignup
1
1

More than 1 year has passed since last update.

【Django】templatesの設定について

Posted at

Django4.0でtemplatesディレクトリをsettings.pyで指定する際に、
少し躓いたところがあったので、記載します。

バージョン

Django: 4.0.4
python: 3.10.2

躓きポイント

まず、templatesディレクトリを作成することで、
templatesディレクトリに入っているhtmlをviews.pyで呼び出すことができます。
ただ、templatesディレクトリに使用する際は、settings.pyでtemplatesの場所をしている必要があります。

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

'DIRS:[]'部分が空になっているため、ここに記載していきます。
ターミナルでpwdした場所を直接記載するでも、
自分の端末のみならいいですが、デプロイする際には個人的な場所なのでエラーになります。
よって、以下のようにする必要があります。

settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ BASE_DIR + '/templates'],

BASE_DIRはsettings.pyの最初の方で定義されており、このプロジェクトが存在する場所になります。
なので、+すればいい感じのパスになるのでは?と思い上記のように記載しました。

ここで、runserverを実行すると以下エラーログが出ました。

    'DIRS': [ BASE_DIR + '/templates'],
TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'

どうやらBASE_DIRは文字列ではないようです。
よってstr()で文字列にします

settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ str(BASE_DIR) + '/templates'],

こちらで、エラーがなくなったので、解決しました。
これが、正しい方法なのかわかりませんが、
解決したので、Djangoの勉強に戻ります。

以上です。

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