Home > Software design >  Static files are not getting loaded in Django
Static files are not getting loaded in Django

Time:09-23

Static files are not getting loaded when running on server. I have tried the whitenoise library and referred to the Documentation (http://whitenoise.evans.io/en/stable/django.html) as well, but no luck. I am new to Django, would appreciate any help. PS: I have also collected the static folder using-

python manage.py collectstatic

Below is what I have in my settings.py

INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_celery_beat',
    'django_extensions',
    'haystack',
    'users.apps.UsersConfig',
    'rest_framework',
    'rest_framework.authtoken',
    'django_db_logger.apps.DbLoggerAppConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

WSGI_APPLICATION = 'server.wsgi.application'

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")

CodePudding user response:

If static files are loading when you run locally, but not on your server, you may need to add something to your web server config. E.g. for nginx:

location /static/ {
    root /path/to;
}

location /media/ {
    root /path/to;
}

More details and an example for Apache at https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/modwsgi/#serving-files

CodePudding user response:

For example, if your STATIC_URL is defined as static/, you can do this by adding the following snippet to your urls.py:

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:

you need to specify in Project/urls.py file

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

urlpatterns = [
    # ... the rest of your URLconf goes here ...
]

# For static file and media
if settings.DEBUG:
    urlpatterns  = static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)
  • Related