当前位置:首页 > Web开发 > 正文

python manage.py collectstatic 遇到重复文件

2024-03-31 Web开发

目录布局:

project ----templates ----app ----manage.py

添加静态资源,目录布局更新为:

project ----templates ----app ----static # 静态资源 --------img --------js --------css ----manage.py

以img举例,引用资源的代码为:

{% load static %} <img src='{% static "img/favicon.png" %}'/> DEBUG = True

django会自动挪用django.views.static.serve()来自动找。

settings.py中指定STATICFILES_DIRS即可:

# settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'app/static/') ] DEBUG = False

django不会自动找了,需要手动添加。

settings.py中指定STATIC_ROOT

# settings.py STATIC_URL = '/static/' STATIC_ROOT = 'static' # project根目录下 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'app/static/') ]

urls.py中手动调django.views.static.serve()

from django.views.static import serve urlpatterns = [ url(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}) ]

此时访谒还是会发明404,因为STATIC_ROOT是在deploy时,统一存放静态资源的目录,此时这个目录根柢就没有文件,需要手动执行collectstatic来拷贝文件。

python manage.py collectstatic

遇到反复文件,会有错误提示:

This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel:

以上就总结了DEBUG=True/False时设置静态文件的要领。

感受有用的同学可以顺手存眷下或点个赞哦!

参考文档:

django.contrib.staticfiles.views.serve:

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

Deploying static files: https://docs.djangoproject.com/en/dev/howto/static-files/deployment/

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/31876.html