yamachan
yamachan

Reputation: 1079

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

I'd like to use an image file as a background-image on Django. But I do not know how. First, I read this and tried to write like following this in a css file.

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

But this does not work.

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

and

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

don't work, too.

How do you usually write css file when you use background-image on css files? Would you please give me some advices?

C:\~~~~~~> dir hello\static\img
2016/09/28  19:56             2,123 logo.png
2016/09/24  14:53           104,825 sample.jpeg


C:\~~~~~~> dir hello\static\css
2016/09/29  20:27             1,577 site.css


C:\~~~~~~> more lemon\settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)


C:\~~~~~~> more hello\templates\base.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "css/site.css" %}" />

Django version: 1.9.2

Upvotes: 51

Views: 142416

Answers (21)

vampirepapi
vampirepapi

Reputation: 15

If your img.jpeg file is located within the static directory, you should use the path /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 the path /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.

Upvotes: -3

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.

Upvotes: 1

Shama Bernard
Shama Bernard

Reputation: 3

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

Upvotes: 0

Abdullah Tahir
Abdullah Tahir

Reputation: 157

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

Upvotes: 14

Ebuka
Ebuka

Reputation: 1

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

on windows shift + f5

Upvotes: 0

Beki
Beki

Reputation: 1746

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.

Upvotes: 3

Rugved Koshiya
Rugved Koshiya

Reputation: 33

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

Upvotes: 0

Javad
Javad

Reputation: 223

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.

Upvotes: 0

Sanjay RD
Sanjay RD

Reputation: 91

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'.

Upvotes: 1

prakhar kesarwani
prakhar kesarwani

Reputation: 1

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

Upvotes: 0

Dibya Darshan Khanal
Dibya Darshan Khanal

Reputation: 65

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;

Upvotes: 1

Dominique Kayumba
Dominique Kayumba

Reputation: 1

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

Upvotes: 0

sadric adigbe
sadric adigbe

Reputation: 66

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")

Upvotes: 0

Space guy
Space guy

Reputation: 415

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");

Upvotes: 1

Mohammed Shabeer
Mohammed Shabeer

Reputation: 11

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

best way I think

Upvotes: 0

doss
doss

Reputation: 1

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

Upvotes: -1

Ankit Maisuriya
Ankit Maisuriya

Reputation: 29

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

Upvotes: -1

zencoder
zencoder

Reputation: 169

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

Upvotes: -1

Simas
Simas

Reputation: 789

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'>

Upvotes: 10

LuKs Sys
LuKs Sys

Reputation: 226

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'
     }

Upvotes: 9

Prakhar Trivedi
Prakhar Trivedi

Reputation: 8526

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

Upvotes: 89

Related Questions