Home > Net >  Can't link my css file in my django project
Can't link my css file in my django project

Time:12-12

index.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'style.css' %}">
    <title>Document</title>
</head>
<body>
    <h1 >This is the Heading</h1>
</body>
</html>

settings.py (my app name is base)

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'base'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'testpro.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR, 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'testpro.wsgi.application'

...
STATIC_URL = 'static/'
STATICFILES_DIRS = BASE_DIR, 'static'

Folder structure is like this:

project folder
    /static
       /style.css

CSS contains a simple color change and it is not working.

I've tried linking the css file in different ways and nothing seems to be working. I don't know how or why but sometimes it suddenly works and then suddenly stops working.

CodePudding user response:

add this to the

and add this to the base(urls.py)

urlpatterns = static(settings.STATIC_URL , document_root=settings.STATICFILES_DIRS)

change STATICFILES_DIRS= BASE_DIR, 'static' to STATIC_ROOT = os.path.join(BASE_DIR,'static')

CodePudding user response:

Instead of this:

STATIC_URL = 'static/'
STATICFILES_DIRS = BASE_DIR, 'static'

Try this:

STATIC_URL = '/static/'

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
  • Related