我有一个 django 应用程序在带有 Nginx 的 docker 容器中运行。我的应用程序的所有静态文件(如 css、js)均已成功找到,并且我的 nginx.conf 文件已按应有的方式配置。但我的 django/admin 静态文件没有被发现。
我找到了this solution ,并按照它所说的尝试:
1) Set both STATIC_URL and STATIC_ROOT in your settings.py
2) Define just a single static entry in your nginx conf (with trailing slashes). No need for a second one that addresses static/admin/:
location /static/ { alias /path/to/static/; }
3) Use collectstatic which should collect admin -> static/admin. It will live under the same location as all the rest of your collected static media.
python manage.py collectstatic
当我这样做时,我的 STATIC_ROOT 会收到管理静态文件,但不会收到我的应用程序静态文件。
我对 docker 卷没有任何问题。 NGINX 容器正在接收 STATIC_ROOT 内容。但我会分享我的 .yml 文件,因为也许您检测到其中有错误。
“manage.pycollectstatic”在我的 cldj/Dockerfile 中运行。
我的文件:
设置.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = ['/proj/static/']
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
nginx.conf:
location /static/ {
autoindex off;
alias /static_files/;
}
docker-compose.yml:
version: '3'
volumes:
static_files:
services:
dj:
build:
context: .
dockerfile: df/cldj/Dockerfile
container_name: dj
volumes:
- ./proj:/proj
- static_files:/proj/static_files
ports:
- 8000:8000
command: gunicorn -w 4 proj.wsgi --bind 0.0.0.0:8000
nx:
build:
context: .
dockerfile: df/nx/Dockerfile
container_name: nx
volumes:
- static_files:/static_files
ports:
- 80:80
- 443:443
depends_on:
- dj
更新
我已经更改了我的 settings.py
,如下 Abhimanyu 所提到的:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
使用docker-compose build
,应用程序容器会根据需要填充collectstatic。但 NGINX 容器收到一个名为“static_files”的空文件夹。
我意识到docker-compose.yml
在应用服务中包含以下几行:
volumes:
- ./proj:/proj
- static_files:/proj/static_files
我将其更改为指向“静态”文件夹(我的STATIC_ROOT
):
volumes:
- ./proj:/proj
- static_files:/proj/static
但是这样,整个 static/
文件夹再次被 static/admin
文件夹覆盖(我丢失了我的应用程序静态文件)
更新2(解决方案)
遵循 Abhimanyu 指令后,我需要使用 $dockervolume rm static_files
删除旧的 static_files
卷。
现在一切正常。
最佳答案
使用STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
然后运行
python manage.py collectstatic
它将在您的项目目录中创建一个名为 static 的文件夹。在那里你会找到所有的 css 和 js 文件
关于python - Djangocollectstatics仅收集管理静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52537767/