user19664934
user19664934

Reputation: 1

Static files are not getting loaded in Django

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")

Upvotes: 0

Views: 116

Answers (3)

Mark Bailey
Mark Bailey

Reputation: 1675

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 and your static folder location:

location /static/ {
    root /home/user/testing;
}

location /media/ {
    root /home/user/testing;
}

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

Upvotes: 1

Parvez Khan Pathan
Parvez Khan Pathan

Reputation: 14

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)

Upvotes: 0

Parvez Khan Pathan
Parvez Khan Pathan

Reputation: 14

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)

Upvotes: 0

Related Questions