Django:PosixPath 对象不可迭代

问题描述

在 Django 3.x 版之前,可以使用 os.path 定义模板、静态和媒体文件夹。进入 settings.py 我有这个配置:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
.
.
.
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates','Dirs': [os.path.join(BASE_DIR,'templates')],.
.
.
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),'static-folder')

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),'media-folder')
MEDIA_URL = '/media/'

STATICFILES_Dirs = [os.path.join(BASE_DIR,'static')]

现在设置已更改,我需要使用 Path

from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

我正在遵循这种新方式,但我认为有些事情对我来说还不清楚。我的新 settings.py 配置是:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates','Dirs': [
            BASE_DIR / 'templates',],.
.
.
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static-folder'

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media-folder'

STATICFILES_Dirs = BASE_DIR / 'static'

但使用该配置我看到此错误

线程 django-main-thread 中的异常:Traceback(最近调用 最后):文件“/usr/lib/python3.8/threading.py”,第 932 行,在 _bootstrap_inner self.run() 文件“/usr/lib/python3.8/threading.py”,第 870 行,运行中 self._target(*self._args,**self._kwargs) 文件“/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/utils/autoreload .py",第 53 行,在包装器中 fn(*args,**kwargs) 文件“/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/core/management/commands/runserver.py ”, 第 118 行,在 inner_run 中 self.check(display_num_errors=True) 文件“/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/core/management/base.py”, 第 392 行,检查中 all_issues = checks.run_checks( 文件“/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/core/checks/registry.py”,第 70 行,在 run_checks 中 new_errors = check(app_configs=app_configs,databases=databases) 文件 "/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/contrib/staticfiles/checks.py",第 7 行,在 check_finders 中 对于 get_finders() 中的查找器:文件“/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/contrib/staticfiles/finders.py”, 第 282 行,在 get_finders 中 yield get_finder(finder_path) 文件“/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/contrib/staticfiles/finders.py”, 第 295 行,在 get_finder 中 返回 Finder() 文件“/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/contrib/staticfiles/finders.py”, 第 57 行,在 init 中 对于settings.STATICFILES_Dirs中的root:TypeError:'PosixPath'对象不可迭代

解决方法

试试这个 - STATICFILES_DIRS = [BASE_DIR / 'static',]