在生产中部署django静态文件

时间:2016-10-24 04:33:33

标签: python css django nginx static

我的django应用程序在Ubuntu 14.04 / nginx 1.10 / django 1.10.2 / uwsgi 2.0.14上运行良好,它也可以加载静态文件(js,css,images),但css文件不适用于我的网站。以下是我的配置。

应用程序结构

example.com/
├── example.com
├── static (generated by collectstatic)
│   └── css
│   └── js
│   └── images
├── templates
└── website
    └── static (django collected from)

uwsgi设置example.com.ini

[uwsgi]
...
socket=/var/www/example.com/uwsgi.sock
chdir=/var/www/example.com
chmod-socket=664
...

nginx.conf

server {
    listen      80 default_server;
    server_name  example.com;

    charset utf-8;
    access_log  /var/log/nginx/access.log;

    error_page  404              /var/www/example.com/template/404.html;
    error_page  500 502 503 504  /var/www/example.com/template/500.html;

    location / {
        uwsgi_pass      unix:///var/www/example.com/uwsgi.sock;
        include         uwsgi_params;
    }

    location /static/ {
        alias /var/www/example.com/static/;
    }
}

setting.py

INSTALLED_APPS = (
    ...
    'django.contrib.staticfiles',
    ...
)

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

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "website/static"),
)

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    ...
]

STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

运行./manager collectstatic后,我可以通过点击浏览器中网页的源路径访问.css文件,并检查access.log,它也返回200,没有任何error.log产生。

"GET /static/admin/css/base.a846c0e2ef65.css HTTP/1.1" 200

我认为静态文件已经由nginx提供了,但它在生产中不起作用(在runserver中工作),是否有任何我错过或正在考虑的配置,或者我应该检查的任何权限?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

根据讨论,缺少中间件类,

setting.py

var emails = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.whitespace,
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California']
});

$('.typeahead-from-email').typeahead({
    hint: true,
    highlight: true,
    minLength: 3
},
{
    name: 'from_email',
    source: emails
});

nginx.conf

MIDDLEWARE_CLASSES = [
  ...
  'whitenoise.middleware.WhiteNoiseMiddleware',
  ...
]