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:
JavaScript
x
11
11
1
├───migrations
2
│ └───__pycache__
3
├───static
4
│ └───website
5
│ ├───css
6
│ ├───img
7
│ └───js
8
├───templates
9
│ └───website
10
└───__pycache__
11
CSS:
JavaScript
1
4
1
.body {
2
background: url('/static/website/img/Racoon.jpg');
3
}
4
HTML:
JavaScript
1
16
16
1
{% load static %}
2
<!DOCTYPE html>
3
<html>
4
<head>
5
<link rel="stylesheet" type="text/css" href="{% static 'website/css/main.css' %}">
6
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
7
<link rel="preconnect" href="https://fonts.gstatic.com">
8
<link href="https://fonts.googleapis.com/css2?family=Russo+One&display=swap" rel="stylesheet">
9
{% block title %}
10
<title> Home </title>
11
{% endblock %}
12
{% block content %}
13
<h1> Home </h1>
14
<p> Homepage of the website </p>
15
{% endblock %}
16
settings.py:
JavaScript
1
2
1
STATIC_URL = '/static/'
2
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:
JavaScript
1
4
1
.body {
2
background: url('/static/website/img/Racoon.jpg');
3
}
4
with
JavaScript
1
4
1
.body {
2
background: url('../img/Racoon.jpg');
3
}
4
../
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.