简体   繁体   中英

How to access static css files with Django

I can't access static files with Django in cmd. I'm getting this error: "GET/'/static/blog/css/main.css HTTP/1.1" 404 2371 . This is the code:

#settings.py

STATICFILES_DIR = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

 #base.html
   {% load static %}
<link rel="stylesheet"  type="text/css" href="'{% static 'blog/css/main.css' %}">

this is my directory
├───blog
│   ├───migrations
│   │   └───__pycache__
│   ├───templates
│   │   └───blog
│   │       └───static
│   │           └───blog
│   │               └───css
│   └───__pycache__
└───HelloDjango
    └───__pycache__

Django and python never lie about the exceptions that they throw it nor does their documentation on how to resolve it. If you refer link they have a very clean approach explaining how to get it up and running in a jiffy.

You need a location where it copies from Django static files to some local folder from where it starts rendering from.

Could this be an issue that you forgot to add the following?

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/',   # -> your homework to figure what this is.
]

How about adding these in your urls.py file

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)

Perhaps you must have done all that but did you tell Django to collect them all by running the following command?

python manage.py collectstatic

AFAIK the preferred structure for the static elements in Django is

.
├── my_app/
│   ├── static/
│   │   └── my_app/
│   │       └── admin-custom.css
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── static/
├── templates/
│   └── admin/
│       └── base.html
└── manage.py

But your dir structure is not you mentioned the Django to collect it from, isn't it?

Try all the above and let me know if it worked out for you.

Another hint:

 <link rel="stylesheet" href="{% static "my_app/admin-custom.css" %}"> # figure out the hint here

If you are using Django 1.11+ than add following code to your settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        ...
    },
]

This will enable django to scan through your apps for searching templates directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM