I’m having trouble loading an image via external CSS on Django. It works fine using inline CSS but I want to understand why it doesn’t work using external one. Any help would be appreciated:
My tree:
├───migrations │ └───__pycache__ ├───static │ └───website │ ├───css │ ├───img │ └───js ├───templates │ └───website └───__pycache__
CSS:
.body { background: url('/static/website/img/Racoon.jpg'); }
HTML:
{% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'website/css/main.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Russo+One&display=swap" rel="stylesheet"> {% block title %} <title> Home </title> {% endblock %} {% block content %} <h1> Home </h1> <p> Homepage of the website </p> {% endblock %}
settings.py:
STATIC_URL = '/static/'
P.S I’m using localhost and image does load via URL: http://127.0.0.1:8000/static/website/img/Racoon.jpg
Advertisement
Answer
replace:
.body { background: url('/static/website/img/Racoon.jpg'); }
with
.body { background: url('../img/Racoon.jpg'); }
../
means parent directory. you first go back to your static/website
folder, and go to img
folder and find your image.
If it is still not working, clear browser history and try again.