css 风格的背景图片来自带有 django 的静态文件

background image in css style from static files with django

我用这个 template 在 django 项目中创建了一个主页,但是我无法正确显示背景图像 (bg.jpg)

背景图像在 css 文件中用作傻瓜:

.wrapper.style3 {
    background-color: #000;
    color: #bfbfbf;
    background-image: url(/media/usr/path_to_project/project_name/home/static/images/bg.jpg);
    background-size: cover;
    background-attachment: fixed;
    background-position: center;
    position: relative;
}

我阅读了这些主题

并尝试了所有的解决方案,但似乎没有一个有效。

我的项目树就像

project_name
- home
- static
--home
---style.css
--images
---bg.jpg
- templates
-- home
---base.html
---home_template.html

在 style.css 文件中,我尝试了以下操作

background-image: url(/media/usr/path_to_project/project_name/home/static/images/bg.jpg);

background-image: url("/media/usr/path_to_project/project_name/home/static/images/bg.jpg");

background-image: url(../images/bg.jpg);

background-image: url("../images/bg.jpg");

background-image: url("{% static 'images.bg.jpg' %});

在我的 base.html 模板中我有:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'home/style.css' %}"/>

在我的 home_template.html 我有

{% block body %}
{% load staticfiles %}

        <section id="two" class="wrapper style3">
            <div class="inner">
                <header class="align-center">
                    <p>Nam vel ante sit amet libero scelerisque facilisis eleifend vitae urna</p>
                    <h2>Morbi maximus justo</h2>
                </header>
            </div>
        </section>

{% endblock %}

奇怪的是,我的 static/images 目录中还有其他图像,这些图像在具有内联样式的模板中显示良好,例如:

<div class="image fit">
<img src="{% static 'images/pic03.jpg' %}" alt="" />
</div>

您应该只使用 background-image: url('/static/images/bg.jpg');,因为 Django 会自动将 /static 映射到正确的文件夹。

有一个处理静态文件服务方式的特殊设置:STATIC_URL

这是正确的使用路径。