Django收集静态文件选项详解 原创 Python开发 2022年5月4日 21:07 夏至未至 1043 当前内容 3487 字,在路上,马上到,马上到 ### 目录 [TOC] ### 收集配置 在项目建立完成后,框架就把结构固定好了,收集静态文件,只需在 settings 中配置,如下: STATIC_URL = '/static/' # 指定静态文件从那些地方收集 STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # 收集后放到哪里 STATIC_ROOT = os.path.join(BASE_DIR, "collect_static_file") 主要就是配置,从哪里收集,收集后放到哪里去,清晰易懂。 > 值得提示的是,项目一般如果默认静态目录是 static 的话,收集后存放的目录,建议不要在是 static,会覆盖项目的静态文件。 ### 收集命令 收集一般命令如下: python manage.py collectstatic 如果你收集静态文件,存放的目录是有内容的,会提示是否覆盖,按情况选择。 这是一般的命令,但是人家有不一般的选项,很重要,最近刚好用到,记录下,首先看下 命令的 help: python manage.py collectstatic --help usage: manage.py collectstatic [-h] [--noinput] [--no-post-process] [-i PATTERN] [-n] [-c] [-l] [--no-default-ignore] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] Collect static files in a single location. optional arguments: -h, --help show this help message and exit --noinput, --no-input Do NOT prompt the user for input of any kind. --no-post-process Do NOT post process collected files. -i PATTERN, --ignore PATTERN Ignore files or directories matching this glob-style pattern. Use multiple times to ignore more. -n, --dry-run Do everything except modify the filesystem. -c, --clear Clear the existing files using the storage before trying to copy or link the original file. -l, --link Create a symbolic link to each file instead of copying. --no-default-ignore Don't ignore the common private glob-style patterns (defaults to 'CVS', '.*' and '*~'). --version show program's version number and exit -v {0,1,2,3}, --verbosity {0,1,2,3} Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output --settings SETTINGS The Python path to a settings module, e.g. "myproject.settings.main". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used. --pythonpath PYTHONPATH A directory to add to the Python path, e.g. "/home/djangoprojects/myproject". --traceback Raise on CommandError exceptions --no-color Don't colorize the command output. --force-color Force colorization of the command output. 选项众多,意思也都很明确,但是最常用的,应该是 clear,这个选项的意思是,在存储收集的静态文件之前,先清理已经存在的静态文件,命令如下: python manage.py collectstatic --clear 这样执行,就不再提示覆盖了,而是提示 `将删除所有文件` python manage.py collectstatic --clear You have requested to collect static files at the destination location as specified in your settings. This will DELETE ALL FILES in this location! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: 对于在发布的服务,可能还需要一个参数,就是跳过各种询问,即 noinput,如下: python manage.py collectstatic --noinput --clear 如此,服务部署后,静态文件就能静默收集了,并且在收集前,会清理上一次收集的静态文件,确保本次升级发布,能收集到最新的静态文件。 本文标题: Django收集静态文件选项详解 本文作者: 夏至未至 发布时间: 2022年5月4日 21:07 最近更新: 2022年5月4日 21:07 原文链接: 许可协议: 署名-非商业性-禁止演绎 4.0 国际(CC BY-NC-ND 4.0) 请按协议转载并保留原文链接及作者 collectstatic(1) 上一个 Docker-compose 控制服务启动顺序 下一个 IntelliJ IDEA 安装与永久激活 当前文章评论暂未开放,请移步至留言处留言。