Static files in Django
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;
}
Terminal 404 error with CSS file
Some configuration is required to load static files.
# settings.py
STATICFILES_DIRS = [BASE_DIR / 'blog/static']
STATIC_URL = 'static/'
# urls.py
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static('media/', document_root=(settings.BASE_DIR / 'media/'))
(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",
]