[Django]-Managing static files in Django 3.1

2👍

Django 3.1 no longer uses os bydefault to join it’s paths. It’s switched to pathlib instead.

This means you can join your folders like this:

STATICFILES_DIRS = (
    BASE_DIR / "static",
)

MEDIA_ROOT = BASE_DIR / "live-static"

And there should be no need to import os in settings.py at all now.

See here for the docs on what’s new in 3.1: https://docs.djangoproject.com/en/3.1/releases/3.1/

0👍

first, write this command, ‘python manage.py collectstatic’ if this didn’t solved your problem then add this lines in your project urls.py

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

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

0👍

I’m also having this issue however, I’ve found that the static files are able to load when they are inside of the projects folder, and the STATICFILES_DIRS are defined as follows:

STATICFILES_DIRS = (str(BASE_DIR.joinpath('static')),)

Perhaps there’s an issue with how the BASE_DIR is defined it looks at the projects folder as the BASE_DIR though I’m unsure.

0👍

This bit of code at the end of the settings.py file did the trick

STATIC_URL = '/static/'
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATICFILES_DIRS = [
    BASE_DIR / "static",
    '/home/fabi/proyectos/butler/static/', #the absolute path to your static fil
]

0👍

To quickly fix this import os at the top of your settings.py file

Another way however, might be to learn more about how pathlib works and update your BASE_DIR, DATABASES, STATICFILES_DIRS, and other files to use the newer, modern approach.
The first way is better if you’re new to Django and works just fine

Leave a comment