1

I know there are many posts about this, but I have been unable to resolve my problem (for example following this: Django static files (css) not working). I can't get my css static file to load on this practice page, css_practice.html.

I have the following structure

djangoAjax
 settings.py
 ...
 djangoAjaxApp
   static
     ok.css
   templates
     css_practice.html

My settings.py:

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = '############################################'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "crispy_forms",
    'djangoAjaxApp',
]

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 = 'djangoAjax.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'djangoAjax.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'), BASE_DIR / "static",
]

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

my html page:

<!DOCTYPE html>
{% load static %}
<html>
<head>
{% comment %} https://www.bing.com/videos/search?q=django+static+css&docid=608004894969656896&mid=E118E7C4ADFE161B3B12E118E7C4ADFE161B3B12&view=detail&FORM=VIRE {% endcomment %}
    {% load static %}
    <link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\static\ok.css' %}">
<title>Page Title</title>
</head>
<body>

<h1 class="ok">My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>

views.py:

# css practice
def cssRender(request):
     return render(request, "css_practice.html")

urls.py:

from django.urls import path
from .views import cssRender

urlpatterns = [
    path('css/', cssRender, name='cssRender'),
]

I imagine I might be messing up the folder structure somehow... there is also a reference in the django docs: https://docs.djangoproject.com/en/3.2/howto/static-files/

about adding

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

But since I am using, django.contrib.staticfiles in settings, I'm assuming this is done automatically.

Currently the page loads, but css is not applied.

Thanks for your help

3 Answers 3

1

settting.py:

STATIC_URL = '/static/'

Only one {% load static %} is enough in your html code:

<!DOCTYPE html>
{% load static %}
  

You have to Copy and Plast your STATIC files (Js, CSS, ...) in your templates.

It will look like that :

djangoAjaxApp
|_migrations
|_templates
|     |_djangoAjaxApp
|           |_css_practice.html
|_static
    |___djangoAjaxApp (directory with the same App name)
         |_(here all your static file)
            

Your HTML will look like this:

<link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\ok.css' %}">

views.py:

# css practice

def cssRender(request):

    return render(request, "djangoAjaxApp/css_practice.html")

urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.cssRender, name='cssRender'),
        ]

djangoAjax urls.py:

from django.conf import settings
from django.contrib import admin
from django.urls import path

urlpatterns = [
    # ... the rest of your URLconf goes here ...
    ]
Sign up to request clarification or add additional context in comments.

Comments

1

Could you please try it.

from django.contrib.staticfiles.urls import staticfiles_urlpatterns


if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()

1 Comment

thanks a lot for your comment @Sevdimali. That did not change anything. not sure why
0

Just to remind you of it, have you tried hard refresh on your browser? I used to miss this when I was a beginner. (You can do it in chrome with ctrl+shift+r).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.