【问题标题】:Django cannot find my static filesDjango 找不到我的静态文件
【发布时间】:2017-10-20 16:56:28
【问题描述】:

我对网络开发比较陌生。我正在尝试构建我的第一个 Web 应用程序。我在 project_root/static 中有我的静态文件夹,但由于某种原因,我在运行服务器时不断收到 404:

未找到:/users/login/js/bootstrap.min.js 例如。

我的 html 顶部和 settings.py 中有 {% load staticfiles %}:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
STATIC_URL = '/static/'                                                                                        
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

谢谢。


编辑:通过以下答案的组合进行修复。谢谢大家!

【问题讨论】:

  • 你在运行开发服务器吗?看看这个答案 -> stackoverflow.com/questions/9181047/…
  • 您的STATICFILES_DIRS 设置是什么?
  • 所以.....我只是想添加一个无用的评论...我来这里是为了寻求相同问题的帮助...在搞砸了我最初拥有的文件结构之后一段时间...我终于用所有资源刷新页面...我不想说这些答案都没有真正帮助...只需检查以确保您的文件结构正确-也许看看@MohitRustagi的答案。

标签: python django twitter-bootstrap web static


【解决方案1】:

继续阅读这篇文章-http://agiliq.com/blog/2013/03/serving-static-files-in-django/

总结:如果“users”是您项目中的应用名称,则创建目录 - 'users/static/js/'。并将 bootstrap.min.js 放入 js/.该文件可在 localhost:8000/static/js/bootstrap.min.js 访问。来试试吧。

【讨论】:

    【解决方案2】:

    将您的静态 js、css 和其他文件放在项目目录中名为 static 的目录中,然后这些设置将起作用:

    # this defines the url for static files
    # eg: base-url.com/static/your-js-file.js
    STATIC_URL = '/static/'
    
    # this is directory name where collectstatic files command will put your app level static files
    STATIC_ROOT = 'staticfiles'
    
    # this is directory paths where you have to put your project level static files
    # you can put multiple folders here
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, "static"),
    )
    

    根据这些设置,您将能够正确访问您的静态文件

    【讨论】:

      【解决方案3】:

      如果 DEBUG=True 是 settings.py 它将不起作用。在这种情况下,Django 期望 Apache/Nginx 处理静态文件。

      【讨论】:

        【解决方案4】:

        在 settings.py 中使用下面的代码

        MEDIA_URL = '/media/'
        STATIC_URL = '/static/'
        STATICFILES_DIRS = (
            os.path.join(BASE_DIR, 'static'),
        )
        STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
        STATIC_ROOT = '/xxx/site/public/static/'
        MEDIA_ROOT =  '/xxx/site/public/media/'
        

        或 在settings.py中删除或评论DEBUG = True

        【讨论】:

          猜你喜欢
          • 2020-05-05
          • 2021-08-27
          • 2014-11-10
          • 2011-08-26
          • 2020-06-22
          • 2021-08-16
          • 2020-06-20
          相关资源
          最近更新 更多