0

I have a CSS class that I need to add a background to it. How do I point my background to the static folder in Django?

E.g:

.background {
	background: url(img/my-background.png) no-repeat;
}

Do I have to add this with a template tag in my base.html instead? Like this:

<style>.background { background: url({% static "img/my-background.png" %}) no-repeat; } </style>
2
  • I think you just have to specify your static directory(with your image) and then you can access your image with a CSS rule, whether it's inline CSS or external. Commented Feb 4, 2016 at 19:56
  • also, is your app named img? Probably not, so your path should most likely be either /static/your_app/my-background.png or in case you opt to use {%load staticfiles%} then it's probably /your_app/my-background.png. Provided that the full path is /your_app/static/your_app/my-background.png Commented Feb 4, 2016 at 20:04

1 Answer 1

2

Why not simply use Relative Path instead ?

1) settings.py

import os
from path import path

SETTINGS_FILE_FOLDER = path(__file__).parent.abspath()

STATIC_URL = '/static/'

STATIC_PATH = os.path.join(SETTINGS_FILE_FOLDER, '../static')

STATICFILES_DIRS = (
   STATIC_PATH,
)

2) app_name/templates/xyz.html

<link href="{{ STATIC_URL }}app_name/css/style.css" rel="stylesheet" >

3) static/app_name/css/style.css

.class-name {
  background-image: url('../img/logo.png');
}

4) and this should be the folder structure:

project_folder
│   settings.py
│   manage.py    
│
└───app_name
│    │   views.py
│    │   urls.py
│    │   ...
│    │
│    ├───templates
│    │   │   xyz.html
│    │   │   abc.html
│    │   │   ...
│
│
static
│
└───app_name
│    │
│    ├───css
│    │   │   style.css
│    │   │   ...
│    │
│    └───img
│    │   │   logo.png
│    │   │   ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.