FileNotFoundError: [Errno 2] 没有这样的文件或目录:'/app/static'

时间:2021-05-07 13:29:18

标签: django heroku

尝试在 heroku FileNotFoundError: [Errno 2] No such file or directory: '/app/static' 上托管我的 django 项目时遇到此错误 这是settings.py:

STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

这是错误:

 File "/app/manage.py", line 22, in <module>
    main()
  File "/app/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle
    collected = self.collect()
  File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect
    for path, storage in finder.list(self.ignore_patterns):
  File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py", line 130, in list
    for path in utils.get_files(storage, ignore_patterns):
  File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files
    directories, files = storage.listdir(location)
  File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 316, in listdir
    for entry in os.scandir(path):
FileNotFoundError: [Errno 2] No such file or directory: '/app/static'

1 个答案:

答案 0 :(得分:0)

STATICFILES_DIRSSTATIC_ROOTMEDIA_ROOT 等之间的区别can be confusing。在您的情况下,您可以先删除 settings.py 的第一行,因为 STATIC_DIR is not a Django settings variable

那么,您问题的实际原因是 Django 的设置变量 STATICFILES_DIRS 中指定的目录不存在:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

在 Heroku 服务器上,此路径为 /app/static,但在您自己的计算机上,它可能位于诸如 $HOME/awesome-django-project/static 之类的位置。在那里创建目录有望解决问题。

或者,您可以完全删除设置 STATICFILES_DIRS 并放置您的静态文件 inside app directories。我个人更喜欢这种方法,因为它使设置更简单,源代码目录更干净。