【问题标题】:Django local static files path puzzleDjango本地静态文件路径拼图
【发布时间】:2012-10-04 20:48:11
【问题描述】:

我正在尝试在开发中本地呈现静态文件。我遵循规则并将样式表放置在我的 Django 项目文件夹中的/static/ 中,设置为STATIC_URL = '/static/'。使用{{ STATIC_URL }} 模板标签有效,并且文档头中呈现的路径指向正确的目录(据我所知),例如:

http://localhost:8000/static/css/bootstrap.min.css

这会返回 404,当然,没有样式。

我从项目根文件夹中的/static 及其内容(即/css/bootstrap.min.css)开始。然后我将它及其全部内容复制到所有其他应用程序目录中,以尝试 Django 可能正在寻找的不同位置。还是 404。

settings.py中的相关设置:

DEBUG = True

STATIC_URL = '/static/'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'south',
    'users',
    'registration',
    'django_extensions',
    'django.contrib.admin',
)

怎么了?

马特

【问题讨论】:

    标签: python django static http-status-code-404


    【解决方案1】:

    您的urls.py 是什么样的?您是否忘记包含静态文件 url?如果您查看有关提供静态文件 https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development 的文档,建议将以下内容放入 urls.py

    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    
    # ... the rest of your URLconf goes here ...
    
    urlpatterns += staticfiles_urlpatterns()
    

    【讨论】:

    • 那行得通。我曾考虑过该选项,但文档中的以下行使我信服:This view is automatically enabled and will serve your static files at STATIC_URL when you use the built-in runserver management command. To enable this view if you are using some other server for local development, you'll add a couple of lines to your URLconf. 因为我使用的是 runserver,所以我推断 URLconf 的东西是不必要的。但你是对的,谢谢。
    • 我很高兴它解决了您的问题,但我阅读文档的方式与您相同,所以我认为这可能不是正确的做法。你的INSTALLED_APPS 中肯定有django.contrib.staticfiles 吗?或者也许你的 urls.py 中有一些东西会捕获之后的所有内容,从而永远无法访问来自 staticfiles 应用程序的 url?
    • staticfiles 是一个已安装的应用程序,如您所说。我没有静态文件上下文处理器,但默认情况下会出现(这就是标签工作的原因)。我在 url 中看不到任何引起问题的东西,但我会在以后的故障排除中活到那个时候。听起来问题很可能就在那里。谢谢!
    猜你喜欢
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2020-12-07
    • 2021-01-19
    • 2020-12-15
    相关资源
    最近更新 更多