Css wont load

There’s a little bit of work to do this site-wide.
Briefly, you’ll add a little bit of middleware, add an entry to your root urls.py file, and run your project using runserver --nostatic

In your root urls.py file:

# Add any of these imports if you don't already have them
from django.views.decorators.cache import cache_control
from django.contrib.staticfiles.views import serve
from django.conf.urls.static import static
from . import settings

# Add this after the rest of your urlpatterns. (Ensure you don't have another url defined for your static files
urlpatterns += static(settings.STATIC_URL, view=cache_control(no_cache=True, must_revalidate=True)(serve))

Create a file in your app directory named middleware.py:

class DisableCacheMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['Cache-Control'] = 'no-store, no-cache, max-age=0'
        return response

Add <your app directory>.middleware.DisableCacheMiddleware to the MIDDLEWARE section of your settings file - preferably near the top if not the top to ensure it overrides any other middleware setting this header.

This seems to work for me.

Ken

In my case it is returnig 404 error ,so what should i do ,I have tried above methods listed on comments ,like running collectstatic but it is not working still
?

I’m guessing that you’re referring to a different project than the original post. In that case,
it might be more helpful to open up a new thread rather than extending this one.

For us to help you with this, we may need to see a good bit of information. This would include:

  • How you running Django? (runserver, runserver_plus, uwsgi, gunicorn, etc)
  • What your template looks like that is trying to load the css.
  • Various settings in your settings.py file
    • DEBUG
    • STATIC_ROOT
    • STATIC_URL
    • STATICFILES_DIRS
  • The directory structure for your project and the location of the css files
  • What operating system you’re using
  • Whether everything else is working (as far as you can tell)
  • Whether it’s all css files not being found, some css files, or if no static files are found.

Also, when posting code or templates here, please do not post images. Copy / paste the text into the post. When pasting code, enclose it between lines consisting of only three backtick - ` characters. This means you’ll have a line of ```, then the code, then another line of ```. This allows the forum software to keep your code properly formatted.

Thanks! This helped.

Thanks, this helped me too.

Hey, I had the similar problem. Try Clearing The CACHE!

If that doesn’t work read the How to manage static files (e.g. images, JavaScript, CSS) | Django documentation | Django again

This is because you have set your debug=False in settings.py

change debug=True and reload it will work

Welcome! We’re happy that you have chosen to join us here in the Django forum.

For the benefit of everyone else reading this thread in the future, I will point out that the original problem was resolved almost three years ago, and that setting debug = True is not always the right answer. (In fact, there is no indication in the original post that DEBUG was even set to False.)

Understanding the full context of a problem in important when trying to identify a solution.

Hi,

I am facing a problem that Django won’t serve static when in production. How to resolve this?

@akhil-pumex I suggest you open a new topic for your issue. Start with describing your production environment and posting your static file-related settings. Include identifying how you are running Django in production and what steps you’re performing for your deployment.

Well, it may be a late response, but what really happened may have not been noted yet:

The author pasted his code here:

<link rel=”stylesheet” href=" {% static 'css/main.css' %} ">

Take a close look in the ”” characteres, these are NOT valid HTML quotes!

The code provided uses:
It is U+201D : RIGHT DOUBLE QUOTATION MARK {double comma quotation mark}

But the HTML parser requires tag attributes to be enclosed by quotes:
U+0022 : QUOTATION MARK {double quote}
U+0027 : APOSTROPHE {single quote; APL quote}

So, the correct must be:
<link rel="stylesheet" href="{% static 'css/main.css' %}">
or
<link rel='stylesheet' href="{% static 'css/main.css' %}">

And NOT:
<link rel=”stylesheet” href=" {% static 'css/main.css' %} ">

It also worthy note, that there is an space after the first HREF quote, what causes the CSS path to be loaded incorrectly, so that it will generate:

<link rel="stylesheet" href="/static/%20css/main.css">

where it must generate:

<link rel="stylesheet" href="/static/css/main.css">

Any other solution may be just ”sorcery”!

Hi All,

I am facing a problem that Django 3.0.7 were css does not display, and it give a 404 status when calling the css, but the path is appear correct. How can i resolve this?

Welcome!

You can start by opening a new topic for this issue. In your post, include your static-related settings from your settings file, the name of the directory where the static files are stored, the portions of your template where you’re referencing those css files, and the part of your runserver log showing the urls attempting to be referenced and returning the 404.

Side note: When posting code, templates, errors, logs, etc, enclose the text between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code (or template, etc), then another line of ```. Do not post images of the code.

I cannot get css to load in my django app. I would appreciate any help. Thank you.

What i have tried:

  1. cleared browser cache many times.
  2. added to my project_directory/settings.py: import mimetypes mimetypes.add_type("text/css", ".css", True)
  3. moved CSS to the home.html file in the head section between <style></style> section to see if it was an issue with the connection to the static directory - no CSS worked.
  4. tried the static folder within the project_directory and within the app_directory.
  5. I have run python manage.py collectstatic
  6. I have checked the console when I launch http://localhost:8000 and no CSS is present anywhere: element { }
  7. I added {% load static %} to both the home.html and the base.html which extends into home.html.

My settings:

  • system: linux ubuntu 20.04
  • I have an image in the static directory that is loading properly, just not the css.
  • I’m running this locally as I alluded to above.

project tree:

├── project directory
│   ├── app_directory
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── __init__.py
│   │   ├── models.py
│   │   ├── tests.py
│   │   ├── urls.py
│   │   ├── views.py
│   ├── manage.py
│   ├── project_directory
│   │   ├── asgi.py
│   │   ├── __init__.py
│   │   ├── settings.py
│   │   ├── urls.py
│   │   ├── wsgi.py
│   ├── venv
│   ├── requirements.txt
│   ├── templates
│   │   ├── home.html
│   │   ├── base.html
│   ├── static
│   │   ├── image.jpg
│   │   ├── styles.css
│   └── static_root

project_directory/settings.py:

DEBUG = True
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_ROOT = BASE_DIR / "static_root"

project_directory/urls.py:

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

urlpatterns = [
    ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

templates/home.html:

{% extends "base.html" %}
{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Title here</title>
  <link rel="stylesheet" href="{% static 'styles.css' %}">
</head>
<body>
{% block content %}
<div class="container">
  <div class="row">
    <div class="col-md-6">
      <h1>Overview</h1>
      <p>text here</p>

      <h2>Highlights:</h2>
      <ol>
        <li>list 1</li>
        <li>list 2</li>
      </ol>

      <img src="{% static 'image.jpg' %}" alt="Image" class="img-fluid">
    </div>
  </div>
</div>
{% endblock content %}

</body>
</html>

templates/base.html:

{% load static %}
<header>
  <a href="{% url 'home' %}">Home</a>
</header>

{% block content %} {% endblock content %}

Start of my static/styles.css:

/* Global Styles */
body {
  font-family: Arial, sans-serif;
  background-color: #f8f9fa;
  color: #333;
  margin: 0;
  padding: 0;
}

.container {
  padding: 20px;
}

/* Header Styles */
h1 {
  font-size: 36px;
  margin-bottom: 10px;
  color: #007bff;
}

h2 {
  font-size: 24px;
  margin-top: 20px;
  margin-bottom: 10px;
  color: #343a40;
}

/* Text Styles */
p {
  margin-bottom: 10px;
}
...

Please open a new topic for this - do not add this on to this existing topic as it’s not related to the original post.