Docker Django 404用于Web静态文件,但对于管理静态文件很好

时间:2016-07-28 04:58:22

标签: python django docker dockerfile docker-machine

请帮我这个docker django配置提供静态文件。

我在Django上运行的Docker项目在提交static files方面遇到了一些问题。

  

管理员视图的所有静态文件都正常加载,但客户端网络视图的静态文件正在抛出404未找到错误。

这是我的 docker.yml 配置详细信息:

web:
  build: ./web
  expose:
    - "8000"
  links:
    - postgres:postgres
  volumes:
    - ./web:/usr/src/app
  ports:
    - "8000:8000"
  env_file: .env
  command: python manage.py runserver 0.0.0.0:8000

postgres:
  image: postgres:latest
  volumes:
    - /var/lib/postgresql
  ports:
    - "5432:5432"

更新

这是管理员静态文件网址的样子: http://developer.com:8000/static/admin/css/base.css 这就是客户端静态文件URL的样子: http://developer.com:8000/static/css/base.css 通过运行django命令collectstatic

,静态目录中的admin文件夹是创建者

我之前使用过此设置,并且工作正常。但是,当我将项目根文件夹移动到另一个目录时似乎有这个问题。

我完全被困在这里,非常感谢你的帮助和反馈。

3 个答案:

答案 0 :(得分:5)

这是 STATICFILES_DIRS 文件中 settings.py 配置的问题。

  

此设置定义了静态文件应用程序在启用 FileSystemFinder 查找程序时将遍历的其他位置,例如如果您使用collectstatic或findstatic管理命令或使用静态文件服务视图。

以下是我的settings.py中的配置:

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

现在我将此代码更新为:

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

每个文件都正常加载。

参考Link

答案 1 :(得分:2)

在处理django中的静态文件时,使用Whitenoise可以让您的生活更轻松。

1.如果您使用的是docker-compose,请将whitenoise添加到您的requirements.txt文件中:

whitenoise==3.3.1

2.在 settings.py

中添加whitenoise到您的中间件应用程序
MIDDLEWARE_CLASSES = [# 'django.middleware.security.SecurityMiddleware','whitenoise.middleware.WhiteNoiseMiddleware',# ...]

请确保在 security.SecurityMiddleware 应用

下面添加此内容

3.最后,在settings.py

中更改以下变量
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATIC_URL = '/static/'

STATICFILES_DIRS = (os.path.join(BASE_DIR,'<app_name>/static'),os.path.join(BASE_DIR, 'static'),)

请务必使用您的应用名称替换。请注意,这仅适用于您的静态文件存储在(例如) my_project / app / static / app / 中。

否则,如果您的静态文件夹位于 my_project / app / static 中:

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
  1. 最后禁用内置的django静态文件服务器,如下所示:

    INSTALLED_APPS = [
    # ...
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    # ...]
    

答案 2 :(得分:0)

当您将项目移动到另一个目录时,静态目录的路径可能现在也不同了。 Django in most scenarios use apache, nginx or some other web servers to serve static files。需要注意的一点是,应该公开访问您的静态目录。我以前经历过这样的问题。我做的是moved static dir to document root mentioned in apache config file

因此,将静态文件移动到apache的doc根目录并更新settings.py中的静态目录,以引用apache doc root中的静态目录。我希望这有帮助。