CSS not found - Error Message in Runserver Mode

When I execute the following command in my terminal and click on my development server:

python3 manage.py runserver

I get the following error:

Failed to load resource: the server responded with a status of 404 (Not Found)
StyleS.Creators.css:1

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/
SECRET_KEY = 'This is not a 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',
    'YouTrade1_App',
]

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 = 'YouTrade1.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 = '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/"

# 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

"""
URL configuration for YouTrade1 project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.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_App/templates/YouTrade1/YT_Creators.html', home1, name='home1'),
    path('', 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):
    return render(request, "YouTrade1/YT_Creators.html")

HTML Page

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



<head>
    <meta charset="UTF-8"/>
    <title>Creators</title>
    {% load static %}
</head>
<body>

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


<br>   
   <h1>We help Content Creators <br />Invest in creators and share their success!</h1>
    <ul>
        <li>Invest in high-growth aspiring creators</li>
    
        <li>Support creators on their way to success</li>
    
        <li>Collect profit from creators' revenue</li>
  
        <li>Diversify your portfolio</li>
    </ul>

</body>

<footer>
    <p>YouTrade</p>
    <a href="infoyoutraders@gmail.com">infoyoutraders@gmail.com</a>
    <p>©2024 by YouTrade</p>
</footer>

</html>


CSS File


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

What directory is “BeYou.jpg” in?

If it’s a static file in one of your static directories, then the url should include the “STATIC_URL” prefix.

Ok let’s try this one straight on. I guess it was because was in a different (wrong) sub-folder…

Ok I changed the folder path for the pic, but still nothing happens.

I changed it to:

YouTrade1_App/static/YouTrade1/BeYou.jpg

Subsequently, I also turned chace off as suggested on some other forums, but still no changes.

You still need to supply the appropriate url in the reference to it. You cannot just refer to it as “BeYou.jpg” as the url - that’s not the url you use to access static files.

So you’re talking about urls.py?
What should be the reference in this case?

No. It’s a static file. You do not create url entries for static files.

I’m referring to the reference to it in the StyleS.Creators.css file.

So is it now that I need to run collectstatic?
Or in what way should I change the URL in my CSS file.
I find no documentation on this :frowning:

Forget the fact that you’re coding a reference to this in a CSS file - that doesn’t make any difference.

A url reference to a static file is going to be the same regardless of whether it’s in an img tag, or a css file reference - or even if you put the url directly in the address bar. The URL is how you refer to that static file.

Review the docs at How to manage static files (e.g. images, JavaScript, CSS) | Django documentation | Django

Sorry, you’re talking about the reference in the HTML file correct? :angel:

Still I referred to it like this, but no changes yet.

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

It looks like it doesn’t find the “BeYou.jpg” - error 404;
I tried to change the color of the font and it works, so it is reading the CSS file, but it is either not finding the image or not authorized. How do I go on from here?

I managed to search for the picture on my HTML directly, not loading it from my CSS file but still it shows like a placeholder now (I set a random weight & height) - still I don’t understand how to pass it through in my CSS first and then as background for my HTML page :cry:

Ok, in my URLs I added the following:

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Still no effect…

If you wanted to enter the url in the address bar to retrieve that image directly by the browser, what url would you use?

Is that the absolute path? "C:// " etc?

Ok, let me try it this way.

You have a reference to a static file that I believe is working (not the embedded jpg, but the reference to this file itself.)

In the url that is rendered, what is the value of the href attribute as it exists in the html page in the browser?

The value of the reference would be:

"{% static 'YouTrade1/StyleS.Creators.css' %}"

That’s what’s in the template.

What’s in the HTML after it has been rendered?

(You can see this by using “view source” in the browser or the browser’s developer tools, after retrieving the page containing this reference.)

Once I render it - in my test runserver space it shows an error like this:


127.0.0.1/:1 Not allowed to load local resource: file:///C:/Users/rinal/PycharmProjects/YouTrade1/YouTrade1_App/static/YouTrade1/BeYou.jpg

On the page referring to the image (BeYou.jpg) there is a strange endless code:

That’s fine. I’m not concerned about that at the moment.

In the web page that was loaded, what is the href attribute for that css file?

Here it is:

href="/YouTrade1_App/static/YouTrade1/StyleS.Creators.css">