1

I'm working on a Django(2.1.7) project in which I need to load some images in css file. Here's what I have so far:

From settings.py:

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/assets/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets'), ]

I have a directory in my main project folder named as assets and also have 'django.contrib.staticfiles' in INSTALLED_APPS and then I have mentioned some images in css as:

background: url('/assets/images/demo.png') center no-repeat;

The image is available in the images folder but not displaying in the template.

What can be wrong here?

6
  • Did you specify {% load static %} at the beginning of your template? Commented Mar 6, 2019 at 14:30
  • the path you specify in your css is relative to your css file path. So this would only work if your css file is in a directory that contains the 'assets' directory. Commented Mar 6, 2019 at 14:31
  • Assuming you also have a /assets/css/ directory where your css file is located, the link to your image should be "../images/demo.png". Commented Mar 6, 2019 at 14:32
  • Hi @RajanSharma, I'm inside the css file where {% load static %} doesn't work and template is working. Commented Mar 6, 2019 at 14:32
  • Hi @dirkgroten I have images folder inside my assets folder`. Commented Mar 6, 2019 at 14:33

2 Answers 2

1

The path you specify in your css is relative to your css file path. So this url would only work if your css file is in a directory that contains the assets directory.

The question is where is your css file. Assuming it's in a /assets/css folder (inside assets), your url should be:

background: url('../images/demo.png') center no-repeat;
Sign up to request clarification or add additional context in comments.

Comments

0

Add below snippet to your urls.py file

# <----------- rest of the code----------->
urlpatterns += static('/assets/', document_root=settings.STATIC_ROOT) + static(
    settings.STATIC_URL, document_root=settings.STATIC_ROOT
)

1 Comment

This is not needed since the OP is using 'django.contrib.staticfiles' so in debug=True mode, runserver automatically finds the static files in the various /static directories of the apps and inside the /assets directory (since he added that to STATICFILES_DIRS). And even then, this should definitely be removed in production settings (so wrap in if settings.DEBUG == True:). And finally, it only serves the files if they're in STATIC_ROOT so you'd have to run collectstatic on your development machine all the time a change is made to static files.

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.