简体   繁体   English

如何在生产中发布Django静态文件

[英]How to post Django static files in production

I cannot get my Django app to pick up static files in production environment. 我无法让我的Django应用程序在生产环境中获取静态文件。

Within settings.py I've specified 在我已指定的settings.py中

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

and I've included django.contrib.staticfiles in INSTALLED_APPS. 我在INSTALLED_APPS中包含了django.contrib.staticfiles

I've run manage.py collectstatic and it is moving the static files to the /var/www/static/. 我运行了manage.py collectstatic ,它将静态文件移动到/ var / www / static /。

The html resulting shows, for example <link rel="stylesheet" type="text/css" href="/static/myStyleSheet.css"> from a django file which had <link rel="stylesheet" type="text/css" href="{% static 'myStyleSheet.css' %}"> . html结果显示,例如<link rel="stylesheet" type="text/css" href="/static/myStyleSheet.css">来自django文件,其中<link rel="stylesheet" type="text/css" href="{% static 'myStyleSheet.css' %}">

It seems to me it should work but I'm clearly missing something. 在我看来它应该工作,但我显然缺少一些东西。 I'm getting 404 errors on the static files. 我在静态文件上遇到404错误。

The django server that we use locally, by running python manage.py runserver is a development server and cannot be used in production. 我们在本地使用的django服务器,通过运行python manage.py runserver是一个开发服务器,不能在生产中使用。

In production we will use a webserver, that gets the request from HTTP/HTTPS port, and based on our configuration, forward the request to the port in which the app server (Eg. gunicorn) runs, which replaces the development server that we use. 在生产中,我们将使用一个Web服务器,它从HTTP / HTTPS端口获取请求,并根据我们的配置,将请求转发到运行应用服务器(例如。gunicorn)的端口,这取代了我们使用的开发服务器。

The problem here is, the app server does not render static files by default. 这里的问题是,默认情况下,app服务器不会呈现静态文件。 So, you have to configure the web server to take care of it. 因此,您必须配置Web服务器来处理它。

In your web server configuration, you have to point the url /static/ to the static root folder. 在Web服务器配置中,您必须将url /static/指向静态根文件夹。 Thus, the web server will render the static files from the folder that it points to 因此,Web服务器将从它指向的文件夹中呈现静态文件

Edit 编辑

Since you are using apache, add this to the apache config to get static files to work 由于您使用的是apache,请将其添加到apache配置中以使静态文件生效

Alias /static /home/user/myproject/static
<Directory /home/user/myproject/static>
    Require all granted
</Directory>

So, here we are aliasing /static to the path to the static root. 所以,这里我们是静态根路径的别名/静态。 Now, a request for /static/css/my.css will be changed as: /home/user/myproject/static/css/my.css and the corresponding file will be sent back 现在,对/static/css/my.css的请求将更改为: /home/user/myproject/static/css/my.css并将相应的文件发回

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM