Problem Applying CSS in Django with Static-Files App

Django static css is not loading on page

settting.py:

STATIC_URL = '/static/'

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

<!DOCTYPE html>
{% load static %}

Why is my django application not serving .css files?

I managed to figure out the issue. While I set everything up for the base.html css code, I forgot to link the dashboard/style.css file into the base.html head tag. So the file was being loaded and everything but the file was not used by the html because of the missing link.

Django doesn't see static css files

I see the comments but I can't answer in them, so I decided to help you via writing answer directly.

Basically what you did wrong is pasting static folder in wrong root directory - your root directory (BASE_DIR) is djangopractice1.

But, if you want to have static directories in the separate apps, you can always set STATICFILES_DIRS to this in settings:

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

Django Not Applying CSS File From App on 404 Page

TLDR:

If you want to serve static files with DEBUG=False using a local development server, you need to use the --insecure flag:

python manage.py runserver --insecure

Why you get the error:

Every time you render html in your browser, behind the scenes a request is made to fetch each of your static files. So in your case, the 404.html template is telling your browser to fetch http://127.0.0.1:8000/static/launcher/dist/css/launcher.css. If your django server doesn't know where that file is, it will respond with the 404.html template instead of the css, which has a MIME type of text/html, and not text/css, hence your error.

Why django can't find the css files:

If you look at the source code for the static function that you call in your urls.py, it looks something like this:

from django.conf.urls.static import static

def static(...):
if not settings.DEBUG:
return []

return [
re_path(...)
]

Which means that the re_path that is used to render static files, is no longer there, since you set DEBUG=False to test your 404.html template...

Credit to Dmitry Shevchenko for the shortcut.

Static CSS files with Django Application Error

Try: python manage.py findstatic --verbosity 2 ldap/style.css to see where Django is looking for your static files.



Related Topics



Leave a reply



Submit