background image in css style from static files with django

Boidot picture Boidot · Feb 7, 2018 · Viewed 8.6k times · Source

I used this template to create a home page in a django project, however I can't have the background image displayed correctly (bg.jpg)

The background image is used as foollows in the css file :

.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;
}

I read these topics

and tried all of the solutions but non of them seems to work.

My project tree is like

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

in the style.css file I tried the following

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' %});

in my base.html template I have :

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

and in my home_template.html I have

{% 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 %}

The strange thing is that I have other images in my static/images directory that are displayed fine in the template with inline styling such as :

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

Answer

Jorjon picture Jorjon · Feb 7, 2018

You should simply use background-image: url('/static/images/bg.jpg');, since Django automatically maps /static to the correct folder.