1

我目前在 settings.py 中有以下内容:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

#add app-specific static directory
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'project/static'),
    os.path.join(BASE_DIR, 'project/apps/blog/static/'),
    os.path.join(BASE_DIR, 'project/apps/users/static/'),
    os.path.join(BASE_DIR, 'project/apps/comments/static/'),
    os.path.join(BASE_DIR, 'project/apps/categories/static/'),
)

我应该在一行中执行此操作吗?非常感谢。

4

2 回答 2

1

您可以添加自定义静态文件查找器来整理您,但通常如果您/static在应用程序中有文件夹,则应该由

django.contrib.staticfiles.finders.AppDirectoriesFinder

记录的

默认将查找存储在 STATICFILES_DIRS 设置(使用 django.contrib.staticfiles.finders.FileSystemFinder)和每个应用程序的静态子目录(使用 django.contrib.staticfiles.finders.AppDirectoriesFinder)中的文件。如果存在多个同名文件,将使用找到的第一个文件

资源

于 2021-01-08T02:35:14.773 回答
0

更好的做法是将所有静态文件放在根目录的同一文件夹中,而不是每个应用程序中:

# ...
├── app1
├── app2
├── project
├── manage.py
├── media
├── requirements.txt
├── static
│   ├── css
│   ├── icons
│   ├── img
│   ├── js
│   └── vendor

然后在你settings.py分配这个变量:

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

staticfiles_dirs设置目录并告诉 Django 在哪里查找您的静态文件,在这个例子中,我们的文件夹在我们的根目录中被命名为 'static',os.path.join将与static.

顺便说一句STATIC_ROOT,通常在生产环境中使用,当您运行“collectstatic”命令时,包括您的 3rd 方应用程序在内的所有静态文件都将被复制到这个“staticfiles”文件夹中。

此外,您可以以类似的方式将每个应用程序的模板放入同一文件夹中:

# root 
└── templates
    ├── app1
    ├── app2
    ├── app3
    ├── base.html
    └── index.html

并在您settings.py的 'templates' 文件夹中添加目录。


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': { # ...
            ],
        },
    },
]

就个人而言,我认为这会更干净。

您可以参考我的项目的文件结构: here

于 2021-01-08T02:41:32.627 回答