skip to Main Content

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


  1. 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/'))
    
    Login or Signup to reply.
  2. (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",
    ]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search