最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python 3.x - static assets not found in Django web application - Stack Overflow

programmeradmin4浏览0评论

I am new to Django. This is my first attempt to set up a project in Django. I have run this application before and all my static files were displaying as expected. But after some time and restarting my machine, the static files are no longer displaying.

The version of Django is 5.1.3

Here is the project structure

And this is the error messages I get

My settings.py is as follows:

"""
Django settings for DebbyrichCollections project.

Generated by 'django-admin startproject' using Django 5.1.3.

For more information on this file, see
.1/topics/settings/

For the full list of settings and their values, see
.1/ref/settings/
"""

from pathlib import Path
from django.conf.urls.static import static

import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See .1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-%0!($(z=yfs)tik4630krj64)m+h7o12@bujz)v+lh5j+3z%7='

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles'
]

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

ROOT_URLCONF = 'DebbyrichCollections.urls'

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR,'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

WSGI_APPLICATION = 'DebbyrichCollections.wsgi.application'


# Database
# .1/ref/settings/#databases

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': BASE_DIR / 'db.sqlite3',
   }
}


# Password validation
# .1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

from django.conf import settings

# Internationalization
# .1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# .1/howto/static-files/

STATIC_URL = 'static/'

STATICFILEDIRS = [
os.path.join(BASE_DIR,STATIC_URL)
] + static(settings.STATIC_URL, document_root=os.path.join(settings.BASE_DIR, 'static'))

# Default primary key field type
# .1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

I am new to Django. This is my first attempt to set up a project in Django. I have run this application before and all my static files were displaying as expected. But after some time and restarting my machine, the static files are no longer displaying.

The version of Django is 5.1.3

Here is the project structure

And this is the error messages I get

My settings.py is as follows:

"""
Django settings for DebbyrichCollections project.

Generated by 'django-admin startproject' using Django 5.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""

from pathlib import Path
from django.conf.urls.static import static

import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-%0!($(z=yfs)tik4630krj64)m+h7o12@bujz)v+lh5j+3z%7='

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles'
]

 MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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',
]

ROOT_URLCONF = 'DebbyrichCollections.urls'

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR,'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

WSGI_APPLICATION = 'DebbyrichCollections.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': BASE_DIR / 'db.sqlite3',
   }
}


# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

from django.conf import settings

# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = 'static/'

STATICFILEDIRS = [
os.path.join(BASE_DIR,STATIC_URL)
] + static(settings.STATIC_URL, document_root=os.path.join(settings.BASE_DIR, 'static'))

# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Share Improve this question edited Jan 18 at 22:29 Josh asked Jan 18 at 22:11 JoshJosh 1,9687 gold badges38 silver badges67 bronze badges 4
  • + static(settings.STATIC_URL, document_root=os.path.join(settings.BASE_DIR, 'static'))? – willeM_ Van Onsem Commented Jan 18 at 22:17
  • @willeM_VanOnsem Removing it did not resolve the issue. I added it while trying to get it to work. But it also did not seem to make any difference though. So, I have removed it and still the issue persists – Josh Commented Jan 18 at 22:22
  • no, removing will indeed not solve the issue. But just removing or adding stuff will almost never fix the issue. – willeM_ Van Onsem Commented Jan 18 at 22:25
  • 1 can you print(BASE_DIR), and check that it points to a directory that contains static/. – willeM_ Van Onsem Commented Jan 18 at 22:40
Add a comment  | 

2 Answers 2

Reset to default 2

After all searches and efforts, I later discovered that the problem was from the spelling of STATICFILES_DIRS in the settings.py file.

STATICFILEDIRS = [os.path.join(BASE_DIR, 'static/')] //Wrong

which is meant to be

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

Thank you to anybody that tried to help resolve this. I hope this will save someone else the trouble and time I spent to discover this

I think you misunderstand how to use the static(…) handler [Django-doc]: this is a tool to define URL paths that then invoke a view to serve the static file, so it does not belong in the settings.py but in the root urls.py (or another one, although that is strange), so the DebbyrichCollections/urls.py looks like:

# DebbyrichCollections/urls.py

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

urlpatterns = [
    # …
]


urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

In the settings, please don't join the STATIC_URL with the BASE_DIR, this does not make much sense, and if you later change the STATIC_URL, it can introduce a lot of trouble.

Work with:

# settings.py

# …

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

Note: Python modules are normally written in snake_case, not PascalCase, so it should be debbyrich_collections, not DebbyrichCollections.


Note: Django does not service static and media files in production. In production, you will need to configure a webserver like Apache or Nginx. The Django documentation has sections on configuring the webservers.

发布评论

评论列表(0)

  1. 暂无评论