48

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

yamachan
  • 1,029
  • 2
  • 12
  • 28
  • 3
    Possible duplicate of [How to refer to static files in my css files?](http://stackoverflow.com/questions/5898776/how-to-refer-to-static-files-in-my-css-files) – timo.rieber Sep 29 '16 at 11:53
  • 1
    You either use a relative path to where the CSS file resides (using `../` to go up), or a relative path to domain root (starting with `/`), or an absolute path (including domain name). – tao Sep 29 '16 at 11:59
  • @timo.rieber Thank you for your comment. I read several same questions in this site, but I couldn't solve it. And I read your link and learned a lot. Thank ou. – yamachan Sep 29 '16 at 12:06
  • @Andrei Gheorghiu Thank you for your advice. Un??? `url("../img/sample.jpeg")` worked now...I don't know why this did not work before...but anyway, I am grateful to your advice. Thank you. – yamachan Sep 29 '16 at 12:09

20 Answers20

84

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

Prakhar Trivedi
  • 8,218
  • 3
  • 28
  • 35
11
background-image: url('{% static ".jpg" %}');
Maelig
  • 2,046
  • 4
  • 24
  • 49
Abdullah Tahir
  • 127
  • 1
  • 4
  • 4
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Apr 27 '20 at 09:11
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'>

MBT
  • 21,733
  • 19
  • 84
  • 102
Simas
  • 642
  • 8
  • 15
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'
     }
LuKs Sys
  • 226
  • 1
  • 5
  • 3
    Thank you for your advice, LuKs Sys. Can I ask you a question? Can I write `{{ STSTIC_URL }}` even in `site.css`? Do I need to write this without `{% load static %}` or something? Or is your last code supposed to be written in html files? – yamachan Sep 29 '16 at 12:14
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,344
  • 1
  • 12
  • 22
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");
Space guy
  • 375
  • 5
  • 14
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'.

AEM
  • 1,354
  • 8
  • 20
  • 30
Sanjay RD
  • 51
  • 2
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
  • 1
0
background-image: url('../img/4799045.jpg');

best way I think

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
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

AEM
  • 1,354
  • 8
  • 20
  • 30
  • From Review: Hi, while links are a great way of sharing knowledge, they won't really answer the question if they get broken in the future. Add to your answer the essential content of the link which answers the question. In case the content is too complex or too big to fit here, describe the general idea of the proposed solution. Remember to always keep a link reference to the original solution's website. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – sɐunıɔןɐqɐp Feb 03 '21 at 12:03
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
  • 213
  • 2
  • 9
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
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 18 '23 at 19:54
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

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 27 '23 at 09:48
-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

zencoder
  • 169
  • 2
  • 13
-2

Just put "/static/../img.jpeg" before the path url