gpt4 book ai didi

python - 样式表未从 Django 中的相对路径加载

转载 作者:行者123 更新时间:2023-11-28 18:28:56 25 4
gpt4 key购买 nike

目前在django中设置了一个文件夹结构:

{appname}\templates\

{appname}\templates\assets\css\

但是当我尝试包含类似 <link rel="stylesheet" href="assets/css/bootstrap.css" /> 的内容时在我的模板中 {appname}\templates\ ,无论出于何种原因,它都没有加载;我可以直接从 Twitter 加载,但如果可能,我更愿意保留相对路径。

为什么这行不通?如果有任何线索,PyCharm 中的子文件夹显示为浅灰色,也不知道为什么会这样。


编辑:好的,所以我读了here关于如何设置静态文件,已经设置好了static我的主元素文件夹下的目录,带有 css文件夹下面。

我更新了 settings.py 以包括:

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
import os.path

STATICFILES_DIRS = (
os.path.dirname(__file__).replace('\\','/'),
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)

然后尝试添加

<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.css" />

到我的 html 文件,但它没有加载 -- 我在这里做错了什么?

最佳答案

您想将您的 css 保存在应用程序根目录中名为 static 的文件夹中。然后确保你有 django.contrib.staticfiles包含在 INSTALLED_APPS 中(在你的 settings.py 中)。现在当你运行 python manage.py runserver ,您的静态文件将在 localhost:8000/static/可用(这由 STATIC_URL 设置定义 - 默认为 static/ )。

您需要确保您使用的是 RequestContext在你看来的对象。这确保来自 settings.py 的变量(例如 STATIC_URL)在模板中可用 -

def your_view(request):
#...
return render_to_response('page.html', context_data, context_instance=RequestContext(request))

(如果您使用新的 render() 快捷方式而不是 render_to_response ,则会为您处理)

如果您在生产环境中提供文件,那么您可以使用 python manage.py collectstatic命令将所有静态文件(即应用程序根目录中名为 static/ 的文件夹中的任何内容,以及 STATICFILES_DIR 中的任何内容)移动到由 STATIC_ROOT 定义的文件夹中.然后让您的网络服务器在 STATIC_URL 提供这些文件(这不是由 django 处理的,事实上 django 文档似乎建议您甚至不要使用为 django 应用程序提供服务的同一个网络服务器)。

您可以将静态文件放在任何您想要的地方,并让 django 管理它们,只需将目录的位置包含在 STATICFILES_DIR 元组中即可。

看看 docs关于提供静态文件。 (我假设你使用的是 django 1.4)

关于python - 样式表未从 Django 中的相对路径加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com