python - Django 中 css 文件调用的图片放在哪里?

标签 python html css django templates

我已经在线下载了一个模板,其中包括基本 html 文件、图像和 css 文件。现在我想在 django 中实现这一切。

到目前为止,我尝试了这样的方法,但没有得到好的结果,页面在没有 css 文件或没有图像的情况下渲染,或者两者都没有......好吧,出了问题

设置.py:

MEDIA_ROOT = rel('resources')
MEDIA_URL = '/resources/'

base.html:

<link rel="stylesheet" type="text/css" href="resources/style.css" />

我已将图像和 css 文件放在 resources 文件夹和 templates 文件夹中,但它不起作用,请帮忙

最佳答案

编辑:

我有点偏离了... STATIC_ROOT 指的是 Django 将收集所有静态文件的目录。 STATICFILES_DIRS 是静态文件的搜索路径列表。像这样:

设置.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 = PROJECT_ROOT + 'static/'

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

# Additional locations of static files
STATICFILES_DIRS = (
    # 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.
    "C:/www/django/static",
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

并将 URL 添加到 urls.py 中:

urlpatterns += staticfiles_urlpatterns()
<小时/>

原始答案:

这可能会很令人困惑。 MEDIA_ROOT 目录用于存放通过文件上传表单上传的文件。对于可通过客户端请求直接访问的物理文件(例如样式表、脚本和图像),您必须使用 STATIC_ROOT 和 STATIC_URL。我认为STATIC_ROOT必须是绝对路径。

设置.py

# the url: myserver.com/static/
STATIC_URL = '/static/'
# refers to this directory: 
STATIC_ROOT = '/home/user/static server files'

假设您将 css 放在“/home/user/static server files/css/”中,然后像这样引用它们:

base.html

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

关于python - Django 中 css 文件调用的图片放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7530207/

相关文章:

python - 如何使用python一次从文件中读取两行

python - 关闭未保存到变量的文件不是 Python 中的坏习惯吗?

python - 如何在 SQLAlchemy 中使用 FROM 对象注释函数元素

python - 基于连续计数的反转值

javascript - Jquery 选择 parent child

jquery - 用css全屏显示可以吗?

html - 将图像和列表分开,使它们在自己的行中

html - Bootstrap 4 - 卡片列中的响应卡片

html - 使用 css transition 滑动效果 - div 在幻灯片之前显示

javascript - 选中复选框时划掉文本