静态文件未在生产中显示

时间:2015-10-10 07:42:53

标签: python django nginx gunicorn

已编辑以显示更新的配置

生产中没有显示静态文件。文件在开发中正确显示

settings.py

BASE_DIR = os.path.dirname(__file__)

STATIC_ROOT = '/opt/soundshelter/static/'

print "Base Dir: " + BASE_DIR #this returns /opt/soundshelter/soundshelter/soundshelter
print "Static Root: " + STATIC_ROOT #this returns /opt/soundshelter/static/


STATIC_URL = '/static/'

STATICFILES_DIRS = (

    os.path.join(BASE_DIR, 'static'),

) #/opt/soundshelter/soundshelter/soundshelter/static

正在应用程序中调用文件 <link href="{% static "css/portfolio-item.css" %}" rel="stylesheet">

使用Nginx和Gunicorn。

Nginx配置:

server {
    server_name 46.101.56.50;

    access_log yes;

    location /static {
        autoindex       on;
        alias /opt/soundshelter/static/;
}

    location / {

        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }

#       error_log /opt/soundshelter/soundshelter/soundshelter/nginx-error.log;

}

正在运行python manage.py collectstatic个报告文件已成功复制,但仍未显示。

由Fabric处理的部署

from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm

env.hosts = []

print "Here we go..."

def commit():
    local("git add . && git commit")

def push():
    local("git push origin master")

def prepare_deploy():

    commit()
    push()

def deploy():
    code_dir = '/opt/soundshelter/soundshelter/'
    with cd(code_dir):
        run("git pull")
        run("python manage.py collectstatic -v0 --noinput")
        run("service nginx restart")
        run("ps aux |grep gunicorn |xargs kill -HUP")
        run("gunicorn -b PROD_IP soundshelter.wsgi:application")

commit()
push()
deploy()

3 个答案:

答案 0 :(得分:1)

首先,在我看来,您编辑的STATICFILES_DIRS指向了错误的文件夹,因为您有/static/个文件夹,而不是/staticfiles/。应该像原来一样:

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

其次,STATIC_ROOT应该指向由pro服务器提供的静态文件夹(但最好不在项目文件夹中)。在你的情况下:

STATIC_ROOT="/opt/soundshelter/soundshelter/soundshelter/static/"

我通常在项目附近放置静态文件夹并使用动态STATIC_ROOT而不是硬编码:

BASE_DIR = os.path.abspath(os.path.dirname(__file__))
#this will alow to collect your static files in /opt/soundshelter/soundshelter/staticfiles/static
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles/static')

现在你应该collectstatic,它将收集STATIC_ROOT目录中的所有静态文件。

答案 1 :(得分:0)

糟糕的解决方案 - 不要在生产中使用

https://docs.djangoproject.com/en/1.8/howto/static-files/

将此添加到urls.py就可以了解

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

答案 2 :(得分:0)

在您的Nginx配置中,您是否尝试设置:

location /static {

而不是

location /static/ {

还要确保运行nginx的用户对静态文件夹具有读取权限。