【问题标题】:Static does not loads static files in DjangoStatic 不会在 Django 中加载静态文件
【发布时间】:2018-11-16 10:13:54
【问题描述】:

这是我的目录结构

app_web
    _init_.py
    settings.py
    urls.py
    wsgi.py
upload_app
    migrations/
    static/
       js/
         alert.js 
    templates/
       upload.html
    _init_.py
    admin.py
    apps.py
    models.py
    tests.py
    views.py
db.sqlite3
manage.py

settings.py 中,我的 STATIC_URL = '/static/'

在我的 upload.html 中

{% load staticfiles %}
<script type="text/javascript" src="{% static "js/alert.js" %}"></script>

它不起作用,每次都会抛出 404 错误。我什至尝试过load static,但它仍然无法从静态文件夹加载任何内容并引发 404 错误。

我使用的是 Windows 10 机器和 Django==1.9

【问题讨论】:

  • 对不起,{% load static from staticfiles %}
  • @WillemVanOnsem 它抛出错误'staticfiles' is not a valid tag or filter in tag library 'static'
  • 虽然 django.contrib.staticfiles 存在于 settings.py 中
  • 您是否在设置中添加了 STATICFILES_DIRS?
  • 修复了,你能不能看看我的回答并根据它提供建议@leelum1

标签: django django-models django-templates


【解决方案1】:

这个想法是在upload_app 文件夹之外创建一个static 目录。原因是在 settings.pyBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 。这意味着上面的一个目录是基本目录,因此它将开始从该目录搜索static/。但它永远不会找到它,因为我放在 upload_app/static 中。

另外,我需要努力将templates 放在应用程序之外upload_app,因为将模板保留在应用程序内通常不是最佳做法。

在结构中寻找其他建议

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-30
    • 2019-01-21
    • 2020-09-10
    • 2017-10-08
    • 2019-07-12
    • 2019-02-23
    • 2017-04-08
    • 2017-11-08
    相关资源
    最近更新 更多