Search code examples
pythondjangodjango-2.0

Django 2 Images from STATIC_URL is not loading in Css


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?


Solution

  • 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;