簡體   English   中英

在 Django 模板中設置 DIRS url 時遇到問題

[英]Having trouble setting the DIRS url in Django TEMPLATES

在我的項目的主文件夾中創建了一個文件夾模板,並試圖為 django 設置一個 url 以在其中查找模板,我收到以下錯誤:

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

在我的 settings.py 文件中,我插入了以下代碼:

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

django的版本是3.1.3

BASE_DIR / 'templates'

這里的斜杠運算符有助於創建子路徑(類似於os.path.join() ),並且此運算符是針對 Path 對象而非字符串實現的。

>>> from pathlib import Path
>>> p = Path("mypath")
>>> print(p / "child")
mypath\child

因此,在您的情況下,您可以將BASE_DIR轉換為Path object。

>>> from pathlib import Path
>>> Path(BASE_DIR) / 'templates'

要么

您可以使用os.path.join(BASE_DIR, 'templates') function 組合兩個路徑字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM