I deployed a django app to heroku, using "git push heroku master" which worked absolutely fine.
I then created a second app on the same git using "heroku create second-app -r staging'
and pushed using: git push staging master
when I open second-app, none of the static files are picked up or loaded (ie no css, js, or images work)
This is extremely confusing - please help!
my settings file is below
import os
import platform
import dj_database_url
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# This should work for any deployment
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))
ADMINS = (
('me', 'me#gmailcom'),
)
MANAGERS = ADMINS
# LOCAL SETTINGS
if platform.system() in ['Windows', 'Darwin']:
#EV = 'LOCAL'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': BASE_DIR + '//db//db.sqlite3',
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake',
'TIMEOUT': 86400,
'OPTIONS': {
'MAX_ENTRIES': 10000
},
}
}
# HEROKU SETTINGS
else:
#EV = 'HEROKU'
# DEBUG = False
DATABASES = {}
DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Todo: ammar - update to Memcached
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake',
'TIMEOUT': 86400,
'OPTIONS': {'MAX_ENTRIES': 10000},
}
}
TIME_ZONE = 'Europe/London'
LANGUAGE_CODE = 'en-gb'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = False
MEDIA_ROOT = ''
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
SECRET_KEY = '***'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'sm.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'sm.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'mytemplates')
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'smcore',
'south',
'django.contrib.humanize',
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/getStarted/'
LOGOUT_URL = '/do_logout/'
# e-mail server
EMAIL_HOST_USER = '***#gmail.com'
EMAIL_HOST= 'smtp.gmail.com'
# EMAIL_PORT = 465
EMAIL_USE_TLS = True
EMAIL_HOST_PASSWORD = '***'
DEFAULT_FROM_EMAIL = '***#gmail.com'
SERVER_EMAIL = '***#gmail.com'
Update
I took a copy of the code and redeployed, which worked with the following updates to the settings:
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
(os.path.join(BASE_DIR,'smcore','static')),
)
STATICFILES_FINDERS = (
#'django.contrib.staticfiles.finders.FileSystemFinder',
#'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
I then branched my code (so I have master and staging) and synced new heroku remote into my staging branch. I then did a git push staging staging:master and it did a full upload; which has once again got me back to the same place... help!!!
Eventually solved this using the below in my urls file - from this question: Heroku - Handling static files in Django app
from <app> import settings
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
I have been dealing with the same problem too. I tried not to use the solution recommended by David since it seems to be used only in development (and not production) (See: Heroku static files not loading, Django)
And here are the 2 things that I changed in my code.
(I'm using Django 1.7)
1) settings.py
I add these lines to the setting files
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
# Add to this list all the locations containing your static files
)
STATIC_ROOT: this tells Django where to (a) put the static files when you run "python manage.py collectstatic" and (b) find the static files when you run the application
TEMPLATE_DIRS: this tells Django where to look for your static files when it search for statics files when you run "python manage.py collectstatic"
2) wsgi.py
Originally my file was:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxxx.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
And I changed it to:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxxx.settings")
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
Read here for more information on whitenoise: https://devcenter.heroku.com/articles/django-assets#whitenoise
Also, remember to install whitenoise:
pip install whitenoise==2.0.6
Before deploying the project, run:
python manage.py collectstatic
This will create a folder indicated by STATIC_ROOT (declared in your settings.py), containing all your static files.
It seems that it's because you're using the staticfiles app without having set the STATIC_ROOT setting.
In comparison, my settings.py is something like:
# Static asset configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '../myapp/static')
You should set the STATICFILES_DIRS too (note that my conf for this var is probably not the same than yours)
Then, push your code and try again.
If it still doesn't work, you can use this to debug :
https://devcenter.heroku.com/articles/django-assets#debugging
Since Django 1.3 you've been able to do the following
# only showing relevant imports
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns(
'',
# your urls go here
)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
For Django 2.1.7, I did the following changes in order to work:
Added whitenoise to requirements.txt in addition to gunicorn
Project settings.py should have the following:
A) static settings:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
B) Add whitenoise to middleware:
MIDDLEWARE = [
.....
'whitenoise.middleware.WhiteNoiseMiddleware',
]
Finally commit and push your changes then deploy your app peacefully.
Related
When running locally my files are correct but on production it seems that none of the changes are through. I might be forgetting to do something to make the production files the same as local. Changed inbox.html to another file name.
TemplateDoesNotExist at /
inbox.html
Request Method: GET
Request URL: https://url.com/
Django Version: 3.2.9
Exception Type: TemplateDoesNotExist
Exception Value:
inbox.html
Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/template/backends/django.py, line 84, in reraise
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.9.6
Python Path:
['/app/.heroku/python/bin',
'/app',
'/app/.heroku/python/lib/python39.zip',
'/app/.heroku/python/lib/python3.9',
'/app/.heroku/python/lib/python3.9/lib-dynload',
'/app/.heroku/python/lib/python3.9/site-packages']
Server time: Tue, 01 Feb 2022 16:02:49 -0800
settings.py
"""
Django settings for portfolio project.
Generated by 'django-admin startproject' using Django 3.2.9.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# 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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
import os
#Gets rid of
from decouple import config
SECRET_KEY = config("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#DEBUG = config('DJANGO_DEBUG',default=True, cast=bool)
ALLOWED_HOSTS = ["url.com",'127.0.0.1','localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'social_django',
'formtools',
'phonenumber_field',
'pages.apps.PagesConfig',
'storages',
'django_cleanup.apps.CleanupConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django_session_timeout.middleware.SessionTimeoutMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware', #new
]
ROOT_URLCONF = 'portfolio.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',
'social_django.context_processors.backends', # <--
'social_django.context_processors.login_redirect', # <--
],
},
},
]
WSGI_APPLICATION = 'portfolio.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/3.2/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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
# Swapped to Canada
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Canada/Pacific'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
# All of this is in my console.aws.amazon to configure aws s3 static files
# If I am in prod DEBUG==false
# IAM Management Console
if DEBUG:
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
# Amazon S3 Buckets
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_DEFAULT_ACL = None
AWS_S3_SIGNATURE_VERSION = 's3v4'
AWS_S3_REGION_NAME = 'us-east-2'
AWS_STATIC_LOCATION = 'static'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)
STATICFILES_STORAGE = 'portfolio.storage_backends.StaticStorage'
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION )
DEFAULT_FILE_STORAGE = 'portfolio.storage_backends.MediaStorage'
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL= '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'pages/static'),
]
# Fixes Found another file with the destination path
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
#'django.contrib.staticfiles.finders.AppDirectoriesFinder', #causes verbose duplicate notifications in django 1.9
)
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
#Adding social logins
AUTHENTICATION_BACKENDS = ['social_core.backends.google.GoogleOAuth2','django.contrib.auth.backends.AllowAllUsersModelBackend',]
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
# Extends default user with additional fields
AUTH_USER_MODEL = 'pages.Profile'
SOCIAL_AUTH_USER_MODEL = 'pages.Profile'
# social auth configs for google
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('GOOGLE_OAUTH2_KEY')
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('GOOGLE_OAUTH2_SECRET')
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/calendar']
SOCIAL_AUTH_JSONFIELD_ENABLED = True
SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {'access_type': 'offline',}
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.social_auth.associate_by_email', # <--- enable this one
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
# Todo:Add a postgresql for prod settings using Amazon RDS Management Console
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=600)
DATABASES['default'].update(db_from_env)
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
SESSION_ENGINE = (
'django.contrib.sessions.backends.cache'
)
"""
SESSION_COOKIE_AGE = 60 # change expired session
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
"""
import django_heroku
django_heroku.settings(locals(), staticfiles=False)
I changed Inbox.html to another file name but running heroku bash seems like nothing changes.
Running bash on ⬢ arundeepchohan... up, run.9168 (Free)
~ $ ls
google-credentials.json manage.py pages portfolio Procfile Procfile.windows requirements.txt runtime.txt
~ $ cd pages
~/pages $ ls
admin.py calendar.py googleCalendarAPI.py migrations __pycache__ templates urls.py
apps.py forms.py __init__.py models.py static tests.py views.py
~/pages $ cd templates
~/pages/templates $ ls
adminControls.html dashboard.html editProfileModal.html Inbox.html sendMessageForm.html
base.html documents.html googleCalendar.html pickUserType.html sidebar.html
bookAppointment.html editProfileForm.html home.html registration
~/pages/templates $ exit
exit
So I added it to Github. Then I used the automatic deploy function from Heroku to connect it to that repository. Which did allow my heroku run bash to pick up the newly generated files. The only issues now are production database values are now not migrated properly.
I'm hosting my Django application on a VPS and I'm using Django Rest Framework and the Django Admin Site.
Everything seemed working running fine (check the below image),
but when I try to click on my API's I'm redirected to a Server Error (500) page.
One thing to notice is that when I'm running the app locally on my machine everything is working fine.
Below is my settings.py if it can help in anyway:
Django settings for thepatron project.
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
import django_heroku
import datetime
from dotenv import load_dotenv
# Initialize environment variables
load_dotenv()
# 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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
try:
SECRET_KEY = str(os.getenv('SECRET_KEY'))
except KeyError as e:
raise RuntimeError("Could not find a SECRET_KEY in environment") from e
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
# VPS
'194.5.159.80',
# the-patron
'the-patron.com'
# Heroku
'https://the-patron-backend.herokuapp.com/',
# Hostinger IP Address
'141.136.43.2',
# Home IP Address
'127.0.0.1',
# Local Frontend Port
'localhost:4200',
]
AUTH_USER_MODEL = 'store.User'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
# CORS_ORIGIN_ALLOW_ALL = False
# CORS_ORIGIN_WHITELIST = (
# 'http//:localhost:8000',
# )
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'django_filters',
'store',
]
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',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
CORS_ALLOW_ALL_ORIGINS = True # If this is used then `CORS_ALLOWED_ORIGINS` will not have any effect
CORS_ALLOW_CREDENTIALS = True
ROOT_URLCONF = 'thepatron.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 = 'thepatron.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
# Database settings to connect to hosted database
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': str(os.getenv('DATABASE_NAME')),
'USER': str(os.getenv('DATABASE_USER')),
'PASSWORD': str(os.getenv('DATABASE_PASS')),
'HOST': '141.136.43.2',
'PORT': '3306',
'OPTIONS': {
'sql_mode': 'traditional',
}
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
if DEBUG:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'store/static/store'),
os.path.join(BASE_DIR, 'staticfiles/restframework'),
]
else:
# The absolute path to the directory where collectstatic will collect static files for deployment.
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# URL to use when referring to static files located in STATIC_ROOT.
STATIC_URL = '/static/'
# MEDIA_ROOT is for server path to store files in the computer.
# This is where the backend loads media like images from
MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles/store/media')
# MEDIA_URL is the reference URL for browser to access the files over Http.
MEDIA_URL = '/media/'
STATICFILES_STORAGE = [
'django.contrib.staticfiles.storage.StaticFilesStorage',
]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.OrderingFilter',
],
'DEFAULT_AUTHENTICATION_CLASSES':
('rest_framework_simplejwt.authentication.JWTAuthentication', )
}
JWT_AUTH = {
'JWT_ALLOW_REFRESH': True,
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3600),
}
# Activate Django-Heroku.
django_heroku.settings(locals())
This works for me
In settings.py
DEBUG = True
I've been trying to solve this error for a very long time. I have a lot of static images that I am trying to open through my website. However, none of the static images will load, and when I look in the console, I see the error Failed to load resource: the server responded with a status of 404 (Not Found)
Does anyone know why this is happening? I have ran collectstatic multiple times, restarted the server, done everything.
urls.py
from django.contrib import admin
from django.urls import path
import posts.views
import sitepages.views
import hackathons.views
import projects.views
import skills.views
from django.conf.urls.static import static
from django.conf import settings
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
#path('blog/', posts.views.blog, name = "blog"),
#path('posts/<int:post_id>/', posts.views.post_details, name="post_details"),
path('about/', sitepages.views.about,name="about"),
path('awards/',sitepages.views.awards,name="awards"),
path('skills/',skills.views.skills,name="skills"),
path('skills/<int:skill_id>/', skills.views.skill_details,name="skill_details"),
path('projects/',projects.views.project,name="projects"),
path('hackathons/',hackathons.views.hackathons,name="hackathons"),
path('',sitepages.views.home,name="home"),
#path('hobbies/',sitepages.views.hobbies,name="hobbies"),
path('internships/',sitepages.views.internships,name="internships"),
path('project_details/<int:project_id>/', projects.views.project_details,name="project_details"),
path('hackathon_details/<int:hackathon_id>/', hackathons.views.hackathon_details, name="hackathon_details")
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Static section of settings.py
"""
Django settings for pranavblog project.
Generated by 'django-admin startproject' using Django 2.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'posts',
'sitepages',
'hackathons',
'projects',
'pagedown',
'skills.apps.SkillsConfig',
'django.forms'
]
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
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 = 'pranavblog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(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 = 'pranavblog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE_ID = 1
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Above is the whole settings.py, as requested. Allowed hosts and secret key were left out on purpose.
Please let me know if you need more information.
Edit:
Here is my project folder structure. The media folder contains a lot of images.
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
You've added a path to serve MediaFiles, not Static Files. You might want to add static(settings. STATIC_URL,document_root=settings. STATIC_ROOT) to your urls.py
Do not use DEBUG=True in production, that is a big "No".
Have you considered using a proxy like NGINX ? You'll be able to cache your static files improving perfomance. Django is not designed to serve Static files.
I believe you're missing this:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
Or maybe not, but that's the only thing I can see you don't have in your settings.
My application sits at the server path /home/myapp/.
The static assets sit at /home/myapp/src/static/ when a python manage.py collectstatic is performed.
It copies assets from /home/myapp/src/assets/.
I have tried with DEBUG both True and False.
When I navigate to the web application at https://test.example.com, it tells me that all of the assets that reside at /home/mpapp/src/assets/ are 404 (Not Found) despite the files being there.
Also, my web server setup is Apache with a reverse proxy to Gunicorn. I'm serving the application with gunicorn wsgi which serves the application at 127.0.0.1:8000, which is where Apache is ProxyPass to. I've tested against a brand new Django application and this setup serves it properly, so it shouldn't be how Apache and Gunicorn are configured.
What I have been doing is:
1) npm start to compile the React front-end assets
2) python manage.py collectstatic to move the assets to /static/
3) Run gunicorn wsgi where the manage.py and wsgi.py reside
Some code would be helpful. Here is my settings.py:
import os
import sys
import json
import datetime
from unipath import Path
from django.core.exceptions import ImproperlyConfigured
# Import JSON file
print(Path(__file__))
with open('./config/config.json') as f:
s = json.loads(f.read())
def get_settings(settings, s=s):
try:
return s[settings]
except KeyError:
error_msg = 'Set the {0} environment vaiable'.format(settings)
raise ImproperlyConfigured(error_msg)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = Path(__file__).ancestor(2)
# Quick-start development settings - unsuitable for production
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_settings('SECRET_KEY')
ALLOWED_HOSTS = [
'*',
]
# Application definition
INSTALLED_APPS = [
# Base packages
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third party packages
'rest_framework',
'rest_framework_jwt',
'webpack_loader',
'tinymce',
# Local packages
'authentication',
'documents',
'contact',
'home',
'results',
'users'
]
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 = 'config.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',
],
},
},
]
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = get_settings('DEBUG')
WSGI_APPLICATION = 'wsgi.application'
# Password validation
AUTH_USER_MODEL = 'authentication.User'
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',
},
]
# REST Framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
# DRF JWT token settings
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
'JWT_ALLOW_REFRESH': True,
}
# Webpack settings
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, './config/webpack-stats.json'),
}
}
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# EMAIL SETTINGS
EMAIL_HOST = get_settings('EMAIL_HOST')
EMAIL_HOST_USER = get_settings('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = get_settings('EMAIL_HOST_PASSWORD')
EMAIL_PORT = get_settings('EMAIL_PORT')
EMAIL_USE_TLS = True
My directory structure looks like the following which is based on Two Scoops:
testapp
assets
bundles
css
app.e1c352f1.css
js
vendor.s63d4f.js
manifrest.5fd4g.js
app.dsr5h4.js
css
bootstrap.css
img
scss
config
config.json
settings.py
urls.py
webpack.config.js
react
index.jsx
static
admin
bundles
css
app.e1c352f1.css
js
vendor.s63d4f.js
manifrest.5fd4g.js
app.dsr5h4.js
css
bootstrap.css
img
rest_framework
scss
templates
index.html
manage.py
wsgi.py
Also, my urls.py if that might be relevant:
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic.base import TemplateView
from home.views import GetHomeAPIView
urlpatterns = [
# Admin URL
url(r'^admin', admin.site.urls),
# API authentication entry point
url(r'^api/auth/', include('authentication.urls', namespace='signin')),
# API /home entry point
url(r'^api/home/', GetHomeAPIView.as_view(), name='home'),
# API /contact entry point
url(r'^api/contact/', include('contact.urls', namespace='contact')),
# API /contact entry point
url(r'^api/users/', include('users.urls', namespace='users')),
# Any requets that come through serve the index.html
url(r'^$', TemplateView.as_view(template_name='index.html')),
]
So not sure 100% what to do.
I have tried changing both STATIC_ROOT and STATIC_URL to the actual path /home/myapp/src/static/ which didn't do anything.
A bit stumped as to how to resolve this and the SO questions I have reviewed have not fixed the issue.
Well, I got things to start loading by doing the following in 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)
Also can be read about here.
https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development
It is working, but that being said, the sections is called "Serving static files during development"... I'm doing this for production.
I've been trying to deploy the static .css files and stuff for a website my classmates and I have been doing. Right now we have kind of crap styling and stuff so we decided to use some code from Bootstrap to make it looks nice.
After editing my settings.py and doing python manage.py collectstatic, the static files were put into the static/ folder. Upon using the runserver command, none of the styling changes have been made. I've been looking on Google for a while but I have not discovered the solution.
I want to get it working on my local machine before I push it to PythonAnywhere.
Any help will be appreciated.
Here is my settings.py file
"""
Django settings for Dreadnaught project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = GOTCHA!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_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',
'TTT'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'Dreadnaught.urls'
WSGI_APPLICATION = 'Dreadnaught.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'Dreadnaught',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = ()
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = (TEMPLATE_PATH,)
If you want to serve your css and js files in production mode you must change Debug true to false.
DEBUG=False
For reference STATIC