[Django]-The way to use background-image in css files with Django

86👍

Use this:

    #third{
     background: url("/static/img/sample.jpeg") 50% 0 no-repeat fixed;
     color: white;
     height: 650px;
     padding: 100px 0 0 0;   
     }

Most probably This will work.Use “/static/” before your image URL and then try them. Thanks

12👍

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

10👍

For some reasons, which I cannot explain the accepted answer did not worked out for me. (I wanted to use a picture as a cover image for the whole body).

However, here is the alternative that has worked for me for anyone that might be useful for someone that will come across.


In a css file, which is located in the static file directory, I have wrote the following:

CSS:

body {
  background: url(../main/img/picture-name.jpg); 
}

You do not have to include *'{% load static %}'* in your css file.

HTML:

  1. include {%load static%} at the top

  2. create a link href to style, as below.

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

👤Simas

9👍

Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.

In you settings.py file define STATIC_URL: STATIC_URL = '/static/'

     {% load static %}
     <img src="{% static "my_app/example.jpg" %}" alt="My image"/>

or

     #third{
          background: url('{{ STATIC_URL }}my_app/example.jpg'
     }

2👍

Setting Background Image URL – Update from 2021.

I am sure most of you are using separate .css files for your styles.
Here is a simple explanation:

You need to set STATIC_URL = '/static/' in your settings.py file to tell Django where to find your static files. ALso, you might already know this since you came this far to find an answers. But here you go:

You need to include {% load static %} in your template.

Now, you want to set background image for an element. Here is a sample static folder structure:

static
│
├───css
│   ├───accounts
│   └───homepage
│           top.css
├───img
│       top-image.png
└───js
        dropdown.js

From top.css file, you want to access img/top-image.png file. Here are all the options you have:

   /* The best option because it also works with cloud storage services like AWS*/
   .my-element {
       background-image: url("/static/img/top-image.png");
    }
   /* It works when Django is serving your static files from local server, not recommended for production*/
   .my-element {
       background-image: url("../../img/top-image.png");
    }

The rest of the examples assume you are writing inline styles or inside <style> tag within your template (not in a separate .css file)

   /* Because it is inside your template, Django can translate `{{STATIC_URL}}`  into a proper static files path*/
   .my-element {
       background-image: url("{{STATIC_URL}}img/top-image.png");
    }
   /* Similarly you can use {% static 'static_path' %} inside your template with no issues*/
   .my-element {
       background-image: url("{% static 'img/top-image.png' %}");
    }

Here you go – many possible ways you can access your static files from css.

👤Beki

1👍

Here is the structure of directories for my project so you can be in context of why i’m using the URL’s i am using and so you can adapt it to your project.
Root directory is the folder than contains the project and apps. I have 4 apps (contacto, galeria, inicio, mapa) and the "WebCalistenia" which is the folder generated when you create a project. There i have static folder with a child called as the father ("WebCalistenia") which has two childs "/css" and "/img"

enter image description here

This is what worked for me.
Firstly you have to {% load static %} on your HTML.

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
...

Now you’ll link the CSS to HTML

    <link rel="stylesheet" href="{% static 'app_name/css/document.css' %}">

Finally on the css file you will write:

background: url("../img/image_name.jpeg");

1👍

Put apostrophe in the start and ending of Django links and it should work.

background: url('{% static "img/sample.jpeg" %}') 50% 0 no-repeat fixed;

1👍

maybe your url path is incorrect if it is correct make your .css file static and after running the server make sure you clear all the cached images and file, you can clear the cache by pressing Ctrl+Shift+Del and ticking just ‘Cached images and files’.

0👍

base.html in body tag

    <body>

{% load static %}

    </body>

style.css

#third{
    background: url("/static/img/sample.jpeg")  50% 0 no-repeat fixed;
    color: white;
    height: 650px;
    padding: 100px 0 0 0;   
}

problem slove

0👍

hello I had some problems I used pycharmS as tool this how I managed to solve the problem
obviously you have to load static in your html file and setup your settings.py for

if all have be done well but the issue is on css file
your image is in folder called img which is under static folder
YOU HAVE TO DO LIKE THIS :
background: Url("../img/myimage.jpeg"); this is the part of your image
don’t put all settings code of the background on the same line

background-repeat: no-repeat;

background-attachment: fixed;

background-position: center;

YOU USE BROWSER LIKE CHROME TO OPEN YOUR PROJECT I USED MICROSOFT EDGE NO CHANGE ON MY PROJECT HAS BEEN APPLIED SIMULTANEOUS

👤doss

0👍

background-image: url('../img/4799045.jpg');

best way I think

0👍

Although the solutions listed here are right I just want to add one more thing you need to clear your browser’s cache(Ctrl + F5) after updating your CSS.
Refer to this link.

Django CSS not updating

0👍

I got the same issue. Just make sure your image is in your CSS directory. Because since you load your CSS file in HTML with {% load static %} that mean every time the CSS file will search for the image in that directory (I was putting my image in outside of the "static directory where live my CSS file" that why it didn’t work). So to be simple put your image in the static directory (your image and CSS file in the same directory of the "static folder")

0👍

I had the same puzzle and I followed above mentioned answers but for some reasons, quotations didn’t work for me.
This is what worked for me in template:

{% load static %}

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

0👍

here is the best solution from Django Documentation, but i post the simple solution anyway:

1- django.contrib.staticfiles should be included in your INSTALLED_APPS in

Settings.py

file.

2- add the following to the end of

settings.py

if it’s not added already.

STATIC_URL = '/static/'

3- in the html file use static to load the image either Via img tag or css.

{% load static %}
<img src="{% static 'my_app/example.jpg' %}" alt="My image">

or

{% load static %}
<style>
    .bgimg {
      background-image: url("{% static 'my_app/example.jpg' %}");
    }
</style>

4- (IMPORTANT)

Create static folder in your app directory and then create directory inside your static folder with the name of your app again and put your image in there. the folders would be the following:

my_app/static/my_app/example.jpg


after all these steps the image should show perfectly fine.

👤Javad

0👍

Instead of adding in .css file you can use html style tag.

Add this at top of your HTML

{% load static %}

In <head> tag add like this

<style>
    #third {
        background: url("{{ STATIC_URL }}img/sample.jpeg") 50% 0 no-repeat fixed;
    }
</style>

It will not broke if in future you change your static file path

0👍

If any of the above answers does not solve your problem try clearing your browser cache.

on windows shift + f5

👤Ebuka

0👍

Try this one
background-image: url(‘{% static "images/image.jpg" %}’);

Replace the images/image.jpg with your exact file path bearing in mind it should be in static files

0👍

From Django’s official tutorial (version 4.2):

For the purposes of this tutorial, we’re using a file named
background.png, which will have the full path
polls/static/polls/images/background.png.

Then, add a reference to your image in your stylesheet
(polls/static/polls/style.css):

body {
    background: white url("images/background.png") no-repeat;
}

I’d guess that this is the currently preferred method, since they teach it that way.

-1👍

In case there’s anyone looking for another way to solve this, you may want to hot-link the image from your server or any image hosting service you have access to. Here’s how I solved this:

  1. Upload the image in an image hosting site or your server (try Drive/Dropbox)
  2. Right click and open the image in a new tab to access the image URL
  3. Copy the image URL with the (.jpeg, .png) extension and paste in your HTML doc.

Here’s an example:

https://images.your-host.com/photos/image-path-here.jpeg

-3👍

If your img.jpeg file is located within your static directory, you should use /static/img.jpeg. This path starts from the root directory, goes into the static directory, and accesses the img.jpeg file.

if your img.jpeg file is located within the root directory, you should use /img.jpeg. This path starts from the root directory and accesses the img.jpeg file directly.

Remember, the path you use depends on where your img.jpeg file is located

Leave a comment