Abstract

在利用 Nginx+uwsgi 部署Django项目之后,发现 admin 模块
的CSS样式、JS等文件访问全部404,丢失找不到原始资源,整理解决方法


错误

nginx 错误日志如下:

1
2
3
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项目开发过程中, setting.py 中配置如下:

1
2
3
4
5
(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' \%\} 等访问静态资源,admin 模块直接注册之后就可以看到效果,如下:

django-admin-1.png

但是配置Nginx之后,结果却成了如下:

django-admin-2.png


解决之道

setting.py 中新增配置 STATIC_ROOT , 然后 执行 python manage.py collectstatic

此时关于static的配置如下:

1
2
3
4
5
6
7
8
# 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"),
)

执行 python manage.py collectstatic 的结果如下:

1
2
3
4
5
6
7
8
9
10
(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项目
中所有涉及到的静态资源,统计放到 STATIC_ROOT 管理访问

此时,修改 Nginx中关于Django项目的static配置为:

1
2
3
4
location /static {
# alias /project/django/simpleblog/static;
alias /opt/nginx/static;
}

最后访问admin模块发现可以带样式的正常访问!