MIME type error with css file and load static showing in plain text - Django on PyCharm IDE

In my HTML template, when I pass it to debug mode, gets the following errors:

  1. Refused to apply style from its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled.;

[MIME Error]== Refused to apply style from ‘http://localhost:63342/YouTrade1/templates/YouTrade1/{%%20static%20’StyleS.Creators.css’%20%}’ because its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled.

  1. ‘{% load static %}’ shows in plain text;

Pics and css files are in YouTrade1/static/YouTrade1 Template is in YouTrade1/templates/YouTrade1

I tried several solutions for the documentation of my static files and none seem to work.
All documentation according to Django best practices.

I don’t manage to understand whether there’s something wrong with either my django project setup (which looks fine), my testing environment (I click debug/run on pyCharm IDE and they said it’s all fine on their side - same with runserver on the terminal, no issue reported) or my HTML script.

I run python3 manage.py collectstatic too and nothing changes. Same with clear cache command on my browser. Error is 404 - not found .css file.

SETTINGS

"""
Django settings for YouTrade1 project.

Generated by 'django-admin startproject' using Django 5.0.2.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = xxx

# 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',
]

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',
    'whitenoise.middleware.WhiteNoiseMiddleware',

]

ROOT_URLCONF = 'YouTrade1.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': os.path.join(BASE_DIR, 'YouTrade1', 'templates/YouTrade1/YT_AboutUs.html',
                             'templates/YouTrade1/YT_Creators.html', 'templates/YouTrade1/YT_Investors.html'),

        '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 = 'YouTrade1.wsgi.application'

# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

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

# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

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/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

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

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

WHITENOISE_MIMETYPES = {
    '.css': 'text/css',
}

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

URLS

from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from .views import home1



urlpatterns = [
    path('admin/', admin.site.urls),
    path('YouTrade1\YT_Creators.html', home1, name='home1'),] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

VIEWS

from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render

def home1(request):
    context = {"YT_Creators": "home1"}
    return render(request, "YT_Creators.html", context)

HTML Page

<!DOCTYPE html>
<html lang="en">

{% load static %}

<head>
    <meta charset="UTF-8"/>
    <title>Creators</title>

</head>
<body>

<link rel="stylesheet" href="{% static 'StyleS.Creators.css' %} ">

</body>
</html>

CSS File

body {
    background-image: url(BeYou.jpg);
}

First, your TEMPLATES settings should only specify non-app directories in the DIRS section. You do not specify individual files or directories that would already be covered by the APP_DIRS.

Second, your static files should not be anywhere within the directory structure covered by the templates. At the app level, there should be separate templates and static directories for the app.

Now, about this issue: You have a file posted here titled “HTML Page”. What is the actual file name of that file?

Also, it would be helpful if you posted the actual log from the server showing all the requests being made for that page, along with any error messages that may be showing up on the console.

Ok sure, great catch! First thing first, there are separate directories for both templates and static in my app directory - I just don’t know how to extract the app tree from my PyCharm :smiley: - any clue on that?
Second point, the settings section I don’t get the difference between non-app directories and how I should change my settings.
Filename is - YT_Creators.html
I can post the logs, but that would come out as an img/jpgORpng - is that fine for you?

Ok, I can trust you on that. What’s the name of your base project directory? What is the name of your app directory?
(Linux has the tree command, and you can use a dir /s /ad to show the directory tree structure on Windows.)

I just realized looking at this again that you’re joining all these together as a single path. This is completely wrong.

For me to be able to advise you here, I need to understand the directory structure of your project, starting with the base directory of the project.

But specifically to address your question, the standard directory structure of a Django project looks something like what is in my post at Is the structure of the project correct? - #2 by KenWhitesell

Using that example as a starting point, the DIRS setting could look like this: [BASE_DIR / 'templates'], because the templates directory in app1 will be searched because of the APP_DIRS setting.

I don’t see your app listed in there. That’s an issue.

First fix these settings issues and try again. Let’s see what we’ve got at that point before worrying about that yet.

However, if there’s still an issue where you would like assistance, copy paste the text from the session, please do not post images. If you can’t get the text from there, then run runserver from a separate console window.

Ok, I’m having a hard time extracting the tree - can I share it with you on my Git?

Sure, I don’t mind taking a look at it there.

The version of the repo that I can see has none of the recommended fixes in it. Once you’ve gotten them all made, I’ll take another look and we can move forward from there.

Oh okay, then could we summarise the fixes I need to take?

I have made separate directories for both ‘templates’ and ‘static’ under the project directory.

App directory is in a separate folder of the project too.

DIRS settings updated (os.path.join deleted);

The areas that may still need fixes:

  1. Installed App - is there anything I need to add?

  2. “TEMPLATES settings should only specify non-app directories in the DIRS section. You do not specify individual files or directories that would already be covered by the APP_DIRS .” looks like the only one undone, could you be clearer on what should be included (or can you post reference where I can get documentation right on that?

Your app directory

The only directories that need to be specified in the DIRS setting are any directories not in an app that contain templates. If all your templates are in the app/templates directory, then this setting can remain blank (an empty list - [])

Also, as an additional note, you need to use the forward slash (/) as the path separator, not the back slash (\).

Ok got it.

Changes implemented. It should be all as per prescription.

Still the same problem however.

When I run python3 manage.py collectstatic I get: “You’re using the staticfiles app without having set the required STATIC_URL setting.”

In debug, static file not loading, " {% load static %} " still showing as plain text.

And what is the STATIC_URL setting in your settings.py file?

Side note: When you’re running in development using runserver with DEBUG=True, you do not need to run collectstatic.

(Side note #2: To try and avoid confusion here, please don’t mix two different issues / situations. If we’re trying to address the static tag issue, let’s stay focused on that.)

I deleted it :smiley: - I only have static_root

STATIC_ROOT = "/static/YouTrade1/"

Sides notes well received!

STATIC_URL is required.

STATIC_ROOT is only needed when using collectstatic for deployment.

Great! I will add that and recommit - what should it point to?

Unless you want to use urls starting with “static” in your application, I’d suggest you use the recommended default: static/

It’s actually not pointing to anything. It’s the prefix that will be used by the static tag to put in front of the static files when building urls.

The runserver static file loader then detects that prefix in the url to know that it should handle that url as a static file rather than as a url to be resolved by the url dispatcher.

Then, in production, you use that setting in your file server to tell it to serve the static files.

Alright, just changed that, clear explanation.

Still getting the same error though… :frowning:

What URL are you trying to access?

Also, in your repo you have:

path('YouTrade1\YT_Creators.html', home1, name='home1'),]

That’s not a correct path - you must use the “/” and not the “\” as the path separator in URLs.

Also, you have:

return render(request, "YT_Creators.html")

You do not have a template by that name in your “templates” directory. It’s in a directory named “templates/YouTrade1”, which means the reference should be to “YouTrade1/YT_Creators.html”

Actually, if your repo is up-to-date, I’m surprised you’re even getting as far as you say you’re getting. Your repo still doesn’t reflect the recommend organization as I referenced above.

Briefly:

Project directory
-- "Inner" project directory
---- settings, wsgi, urls files
-- "App" directory
---- models, views, templates, static, forms, etc

Ohh - okay here it is applied. Thanks for this in-depth analysis.

You can have a look at it on my repo.

Still the same problem tough.

I still need an answer to this question:

What URL are you trying to access?

It would also be helpful if you posted the complete runserver log showing the output being received.

python3 YouTrade1 runserver

C:\Users\rinal\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\python.exe: can’t find ‘main’ module in ‘C:\Users\rinal\PycharmProjects\YouTrade1\YouTrade1’

Is it this one?

I run it on a local server automatically created on my Chrome from Pycharm usually