I am trying to create a Django project. I created the application under the name blog. In it I have created static and templates folders. static folder has CSS folder where CSS file. It is attached to an HTML template, but none of the CSS styles work when running the localhost.8000 server.
Simple HTML
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
</head>
<body>
<h1>Hello</h1>
</body>
</html>
Simple CSS
h1 {
color: red;
font-size: 35px;
}
I found that the problem occurs when I add "localhost:8000" or "127.0.0.1" to the ALLOWED_HOSTS list in my settings.py file.
ALLOWED_HOSTS = ["localhost:8000", "127.0.0.1"]
2
Answers
Some configuration is required to load static files.
(1)
Firstly is your css file named styles.css ?
(2)
Is your folder structure similar to as follows:
blog/
static/
css/
styles.css
templates/
your_template.html
(3)
Does this reflect your settings.py:
STATIC_URL = ‘/static/’ # Base URL for static files
Ensure STATICFILES_DIRS is correctly set
STATICFILES_DIRS = [
BASE_DIR / "blog" / "static",
]