【问题标题】:Deploying Django, Static files path部署 Django,静态文件路径
【发布时间】:2014-05-26 00:16:18
【问题描述】:

我正在尝试将我的 django 应用程序部署到我的 VPS。所以我按照本教程(link)进行操作,我遇到的唯一问题是我的静态文件无法显示。

我可以看到我的静态文件(所以 nginx 工作正常): 例如:http://188.xxx.xxx.93/static/css/bootstrap.css

但是当我访问我的网站时,我可以看到它链接了一个这样的 css 文件: <link href="/static/css/bootstrap.css" rel="stylesheet"> 所以它试图找到文件(使用端口):http://188.xxx.xxx.93:8001/static/bootstrap.css 这显然不起作用。为了使静态文件正常工作,我应该对我的 django 设置进行哪些更改?

您可以在下面找到我在 VPS 上的文件结构。

Virtual Env: /opt/myapps/

Django project: /opt/myapps/uniprogress/

Static Files: /opt/myapps/uniprogress/static/

Nginx 配置:/etc/nginx/sites-available/uniprogress

server {

server_name 188.xxx.xxx.93;

access_log off;

location /static/ {
    alias /opt/myapps/uniprogress/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"';
}
}

最后在我的 django settings.py 中:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_ROOT = '/opt/myapps/uniprogress/static/'
STATIC_URL = '/static/'

我也使用了:python manage.py collectstatic,但我的静态文件仍然不会显示。

【问题讨论】:

    标签: django deployment static


    【解决方案1】:

    我正在阅读另一个教程link,我发现 STATIC_URL 可以是这样的: STATIC_URL = 'http://static.example.com/'

    所以我猜这个解决方案是这个?

    如果有经验的人可以告诉我这是正确的方法还是不正确的方法?

    附言。我现在在我的网站上的 css 文件是这样的:

    <link href="http://188.xxx.xxx.93/static/css/bootstrap.min.css" rel="stylesheet">.

    【讨论】:

    • 是的,这正是您应该做的。 STATIC_URL 定义要添加到静态文件的前缀。
    【解决方案2】:

    我建议您阅读以下文档,这将有助于更好地理解 Django 静态文件。 http://bitsoul.com/2012/10/04/understanding-django-static-files-for-beginners/

    【讨论】:

      【解决方案3】:

      我建议您以不同的方式进行操作,以便您的整个项目可以移植。在 settings.py 中,有一个例子:

      # Get the current directory
      BASE_DIR = os.path.dirname(os.path.dirname(__file__))
      
      # Define the URL path
      STATIC_URL = '/static/'
      
      # Join the BASE_DIR with static, which means you can move the project folder anywhere
      STATICFILES_DIRS = (
          os.path.join(BASE_DIR, "static"),
      )
      

      我希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2016-04-16
        • 2018-09-04
        • 2014-06-08
        • 2012-06-09
        • 2012-10-04
        • 1970-01-01
        • 2017-03-01
        • 2017-03-05
        • 1970-01-01
        相关资源
        最近更新 更多