Rem
Rem

Reputation: 379

django 1.11.3 css background image not showing

I am trying to have my background image show using css in django 1.11.3 and have received some 404 errors in the terminal when running the server that the picture can't load. My css file does load and can change the contents in my home.html file.

home.html

{% extends 'layout.html' %}
{% load static %}
{% block content %}

<div class="container-fluid">
  <div class="row img-bg">
    <div class="col-sm-12">
      <a href='#'>My Button</a>
    </div>
  </div>
</div>

CSS -

.img-bg{
  background: url('../img/logo.png'); // 404 error
  background: url('../assets/img/logo.png'); // 404 error
  background: url("{% static 'img/logo.png' %}"); // 404 error
  background-size: 100% auto;
  height: 100px; 
  width: 100px;
}

settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'),
)

folder structure

website_src
  --assets
    --css
      --style.css
    --img
       --logo.png

Upvotes: 2

Views: 7748

Answers (3)

Azmol
Azmol

Reputation: 477

Django 3.0.5

I've learned to do the following...

# settings.py
STATIC_ROOT= os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'your+project/static')
]

So you can just add background images without single quotes or using /static/img/image.jpg.

  • Make sure you have run python manage.py collectstatic after changes or inserting CSS files.
  • There are two static folders that need to have had the same change, one in the root and one in the main folder named after your project.
  • Make sure you're not using background: url(../img/image.jpg) no-repeat top center fixed/cover; instead, use background: url(../img/showcase.jpg) no-repeat top center fixed;. Which I believe is a browser CSS compatibility issue, more specific on chrome.
  • You can always use inline styling and point to the source with /static?<section id="showcase" style="background: url('/static/img/showcase.jpg') no-repeat top center fixed;">.

Upvotes: 4

Srinivas
Srinivas

Reputation: 554

Change in your css file because you are serving all your files in assets via /static/

.img-bg{
  background: url('/static/img/logo.png');
  background-size: 100% auto;
  height: 100px; 
  width: 100px;
}

Upvotes: 5

almost a beginner
almost a beginner

Reputation: 1632

Change the following:

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'),
)

To:

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

and then python manage.py collectstatic, see if this helps.

Upvotes: 0

Related Questions