Abstract
在利用
Nginx+uwsgi
部署Django項目之后颗胡,發(fā)現(xiàn)admin
模塊
的CSS樣式、JS等文件訪問全部404,丟失找不到原始資源,整理解決方法
錯誤
nginx 錯誤日志如下:
2017/08/08 11:50:21 [error] 2236#0: *82 open() "/project/django/simpleblog/static/admin/js/change_form.js" failed (2: No such file or directory), client: 106.37.207.126, server: 139.198.11.232, request: "GET /static/admin/js/change_form.js HTTP/1.1", host: "139.198.11.232:8080", referrer: "http://139.198.11.232:8080/admin/blog/blog/4/change/"
... ...
2017/08/08 11:51:27 [error] 2236#0: *89 open() "/project/django/simpleblog/static/admin/css/base.css" failed (2: No such file or directory), client: 106.37.207.126, server: 139.198.11.232, request: "GET /static/admin/css/base.css HTTP/1.1", host: "139.198.11.232:8080", referrer: "http://139.198.11.232:8080/admin/blog/blog/"
解析
在Django項目開發(fā)過程中怨酝, setting.py
中配置如下:
(djangoblog) [root@i-pz58c8g2 simpleblog]# tail -4 simpleblog/settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
在 template
中使用 {% load static %}
可以通過 {% static 'css/django.css' %}
等訪問靜態(tài)資源,admin
模塊直接注冊之后就可以看到效果中狂,如下:
但是配置Nginx之后凫碌,結(jié)果卻成了如下:
解決之道
在 setting.py
中新增配置 STATIC_ROOT
, 然后 執(zhí)行 python manage.py collectstatic
此時關(guān)于static的配置如下:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_ROOT = '/opt/nginx/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
執(zhí)行 python manage.py collectstatic
的結(jié)果如下:
(djangoblog) [root@i-pz58c8g2 simpleblog]# python manage.py collectstatic
Copying '/project/django/simpleblog/static/static/css/bootstrap.min.css'
Copying '/project/django/simpleblog/static/static/css/bootstrap-theme.min.css'
Copying '/project/django/simpleblog/static/static/css/django.css'
... ...
... ...
Copying '/root/.pyenv/versions/djangoblog/lib/python3.5/site-packages/django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js'
Copying '/root/.pyenv/versions/djangoblog/lib/python3.5/site-packages/django/contrib/admin/static/admin/js/admin/DateTimeShortcuts.js'
95 static files copied to '/opt/nginx/static'.
可以看出 python manage.py collectstatic
的作用是收集Django項目
中所有涉及到的靜態(tài)資源扑毡,統(tǒng)計放到 STATIC_ROOT
管理訪問
此時胃榕,修改 Nginx中關(guān)于Django項目的static配置為:
location /static {
# alias /project/django/simpleblog/static;
alias /opt/nginx/static;
}
最后訪問admin模塊發(fā)現(xiàn)可以帶樣式的正常訪問!