Home > Blockchain >  Django 404 css file
Django 404 css file

Time:08-20

For a long time I tried to solve the problem with loading all my static files. When I found a working solution, all svg started loading, but css files didn't.

Here is my settings.py (showing you only main things)

import mimetypes
mimetypes.add_type("text/css", ".css", True)
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = False
STATIC_URL = '/static/'
if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else: STATIC_ROOT = os.path.join(BASE_DIR, 'static')

Here is my urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url

from django.conf import settings

from django.views.static import serve

urlpatterns = [
    path('', include('main.urls')),
    url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),       
]

Here is an example of using css files in my templates

{% load static %}
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/bootstrap-grid.min.css">
    <link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
    <link rel="stylesheet" type="text/css" href=" {% static 'css/main.css' %}">

And this is the error in Chrome Console

Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

And also i cant open css files in a new tab. I am getting that error enter image description here

Also, if you remove from the address bar, then I will open the css file

P.S. I am trying to deploy it

CodePudding user response:

1- Try to replace a slash forward path

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

2- whitenoise

pip install whitenoise

Then, set it to "MIDDLEWARE" in "settings.py". Finally, CSS is loaded successfully:

MIDDLEWARE = [
    # ...
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware", # Here
    # "whitenoise" will solve "MIME type" error then CSS is loaded successfully:
]

3- change your static URL like that:

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)

CodePudding user response:

I think your mistake is that you put in a space in front of your static link

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

Try removing the space in front of {% so it will become

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

is translated to a space character in URL's, so that why I think that's the issue

  • Related