I got my app to deploy, but pages that require an id in session are not rendering. When I set debug = true, everything works fine. Otherwise, I get error 500 message. I've tried many different solutions to no avail.
I imagine the problem is somewhere in my settings.py so I have included that below. I was also able to log the startup so that is included as well.
The main page and pages that don't get a request.session passed into them work fine, as well as functions that update the database. Only pages that require an id passed into the path are not working.
update:
I ran the logentries extension for heroku and found an error on this line:
File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 420, in stored_name
raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name)
ValueError: Missing staticfiles manifest entry for '/css/bootstrap.min.css'
I still don't know what to do
import dj_database_url
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'wiki_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.postgres',
]
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'coding_dojo_final_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'coding_dojo_final_project.wsgi.application'
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': '***',
'HOST': 'localhost',
'PORT': '****',
}
}
WHITENOISE_USE_FINDERS = True
...
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': ('%(asctime)s [%(process)d] [%(levelname)s] '
'pathname=%(pathname)s lineno=%(lineno)s '
'funcname=%(funcName)s %(message)s'),
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'simple': {
'format': '%(levelname)s %(message)s'
}
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
'django.request': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
}
}
STATIC_URL = '/static/'
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
not exactly sure, but something went wrong when I compiled all my static filed. I had to...
+ STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
- STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Related
Anytime I turn debug to false in my settings.py my site gives a server error. This is what my server shows and the site doesn't work again but when debug is true it works perfectly, I don't know what's wrong anyone with ideas on what might be going wrong
Performing system checks...
System check identified no issues (0 silenced).
October 21, 2022 - 23:47:07
Django version 4.1.2, using settings 'dlcfogbomoso.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[21/Oct/2022 23:47:09] "GET / HTTP/1.1" 500 145
[21/Oct/2022 23:54:18] "GET / HTTP/1.1" 500 145
This is my settings.py file check it out for any error(s):
from pathlib import Path
import os
from decouple import config
from django.core.management.utils import get_random_secret_key
# 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/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "Django-insecure-)=l1an%f&lb0+7z#!5l!ang_l!76ahs4eb-$((lt7vo1-mv0(*"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"whitenoise.runserver_nostatic",
"django.contrib.staticfiles",
"myapp",
]
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",
]
ROOT_URLCONF = "dlcfogbomoso.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [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 = "dlcfogbomoso.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "dlcfogbomoso",
"USER": "postgres",
"PASSWORD": "admin",
"HOST": "localhost"
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.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/4.1/howto/static-files/
STATIC_URL = "/static/"
MEDIA_ROOT = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Please what am I doing wrong?
Not a definitive answer, but help. too long for comment
Go into your settings.py and add the code block below. This overrides the default Logging settings to output errors to the console even when debug is set as False. If you already have a LOGGING dict in the settings, just comment it out
Note: defaults are commented out, I just disabled the filters & disabled the existing default loggers
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
# 'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'formatters': {
'django.server': {
'()': 'django.utils.log.ServerFormatter',
'format': '[{server_time}] {message}',
'style': '{',
}
},
'handlers': {
'console': {
'level': 'INFO',
#'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
},
'django.server': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'django.server',
},
'mail_admins': {
'level': 'ERROR',
#'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django': {
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
},
'django.server': {
'handlers': ['django.server'],
'level': 'INFO',
'propagate': False,
},
}
}
I have a model that takes a File Field which is uploaded in Django admin. I noticed that the files save in the proper folder. But when Debug is set to False, I cannot access the file from the admin area or from the front end user interface. I get an error message that says "The resource could not be found on the server."
The app is hosted on Heroku and does the same thing in localhost and live. I read in another post that Whitenoise would work with Heroku but it hasn't resolved the issue. Could someone please point me in the right direction to a fix? The relevant files are below.
Update: Adding urls.py
urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
from .views import DatasetListView
from django.conf import settings
import pages.views
urlpatterns = [
path('', include('pages.urls')),
path('users/', include('users.urls')),
path('accounts/', include('allauth.urls')),
path('admin/', admin.site.urls),
path('downloads/', views.DatasetListView.as_view(), name='downloads'), # where users download the files
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
models.py
from django.core.files.storage import FileSystemStorage
from django.db import models
class DataSet(models.Model):
title = models.CharField(max_length=255)
date_added = models.DateField(auto_now=True)
file_size = models.CharField(max_length=20)
file_type = models.CharField(max_length=20)
data_file = models.FileField(upload_to='delivery/')
def __str__(self):
return self.title
settings.py
import os
import django_heroku
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = Redacted
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'django.contrib.sites',
# third-party apps
'anymail',
# project apps
'pages',
'users',
'allauth',
'allauth.account',
'allauth.socialaccount',
]
AUTH_USER_MODEL = Redacted
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',
]
ROOT_URLCONF = 'myapp.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',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'myapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'Redacted',
'USER': 'Redacted',
'PASSWORD': 'Redacted',
'HOST': '/Redacted',
'PORT': 'Redacted'
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'mysite.log',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers':['file'],
'propagate': True,
'level':'DEBUG',
},
'MYAPP': {
'handlers': ['file'],
'level': 'DEBUG',
},
}
}
# Configure Django App for Heroku.
django_heroku.settings(locals())
Thanks for your help.
I am really novice with Django, and I am having troubles in configuring my app to send me emails with the bug reports.
I already set on the settings file the required variables as I saw on the Django documentation, like this:
DEBUG = False
...
ADMINS = [('myname', 'myemail#server')] # For server errors
MANAGERS = [('myname', 'myemail#server')] # For missing pages errors
I provoked a error for testing, but nothing happened, no email. What should I do?
This is the code of the settings file (without sensitive data, of course):
"""
Django settings for genform project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '****************************************'
DEBUG = False
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'widget_tweaks',
'generador',
'menu',
'parametros_transformados',
'seguridad',
'tablas_de_no_parametros',
'reportes',
'logger',
'parametros',
'django_openid_auth'
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
AUTHENTICATION_BACKENDS = (
'django_openid_auth.auth.OpenIDBackend',
'django.contrib.auth.backends.ModelBackend',
)
TEMPLATES = [
{
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS':[os.path.join(os.path.dirname(__file__), '../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',
],
},
},
]
OPENID_UPDATE_DETAILS_FROM_SREG = True
ROOT_URLCONF = 'genform.urls'
WSGI_APPLICATION = 'genform.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '*****',
'USER': '******',
'PASSWORD': '******',
'HOST': '***********',
'PORT': '***',
}
}
STATICFILES_DIRS = (
#os.path.dirname(__file__)+"static",
# Put strings here, like "/home/html/site_media" or "C:/www/django/site_media".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(__file__), '../static'),
)
AUTH_PROFILE_MODULE = 'seguridad.c_perfil_usuario'
LOGIN_REDIRECT_URL = '/index'
OPENID_SSO_SERVER_URL = '***********'
OPENID_CREATE_USERS = True
LANGUAGE_CODE = 'es-es'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
ADMINS = [('MyName', 'myemail#server')]
MANAGERS = [('MyName', 'myemail#server')]
What's your LOGGING configuration?
I use the following in my production environment:
ADMINS = [
('Admin1', 'admin1#mail.com'),
('Admin2', 'admin2#mail.com')
]
MANAGERS = ADMINS
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # for testing
EMAIL_HOST = 'relay.server.com'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(thread)d %(message)s'
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false', ],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins', ],
'level': 'ERROR',
'propagate': True
},
'django.security.DisallowedHost': {
'level': 'ERROR',
'handlers': ['console', 'mail_admins', ],
'propagate': True
}
}
}
Make sure you have a valid EMAIL_BACKEND defined. You can use a service like mailgun or even gmail if you don't have a own SMTP server (EMAIL_HOST).
Thoese settings look correct, but there are other things that may be holding you up.
Email info in settings.py may not be configured
You have overwritten the default log settings in settings.py and are not writing errors to the email log.
If one or both of these are not setup correctly, then you won't get the emails.
To fix 1 you can look at this answer: https://stackoverflow.com/a/4642194/4788717
To fix 2, you can check out the docs: https://docs.djangoproject.com/en/dev/topics/logging/ and make sure you have either the default or mail admins case:
LOGGING = {
...
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['special']
...
}
I am trying my hands on this example for websockets in Django, https://github.com/jacobian/channels-example as I have intention to use it my production application as well which is hosted in Heroku, and using Whitenoise there.
So, after cloning the above mentioned example, I did some tweaks using Whitenoise, but now on first visit to the application through any browser (chrome or FF) the static files doesn't load and when I refresh again it loads static files, and in third load it again goes off and so on.
Here is my settings file:
import os
import random
import string
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
SECRET_KEY = os.environ.get("SECRET_KEY", "".join(random.choice(string.printable) for i in range(40)))
DEBUG = os.environ.get("DEBUG", False)
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
'chat',
)
MIDDLEWARE_CLASSES = (
'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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'chat.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',
],
'debug': DEBUG,
},
},
)
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': dj_database_url.config(default="postgres:///channels-example", conn_max_age=500)
}
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/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# Channel settings
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
},
"ROUTING": "chat.routing.channel_routing",
},
}
# Logging
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'propagate': True,
'level': 'INFO'
},
'chat': {
'handlers': ['console'],
'propagate': False,
'level': 'DEBUG',
},
},
}
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
Here is the other file which I made changes to routing.py:
from channels.staticfiles import StaticFilesConsumer
from . import consumers
channel_routing = {
# This makes Django serve static files from settings.STATIC_URL, similar
# to django.views.static.serve. This isn't ideal (not exactly production
# quality) but it works for a minimal example.
# 'http.request': StaticFilesConsumer(),
# Wire up websocket channels to our consumers:
'websocket.connect': consumers.ws_connect,
'websocket.receive': consumers.ws_receive,
'websocket.disconnect': consumers.ws_disconnect,
}
Procfile is:
web: daphne chat.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2
worker: python manage.py runworker -v2
I have not tried it on Heroku as if now, just on localhost I observed this behavior so didnt even integrate the solution with original application. I used heroku local to run the application locally.
What am I doing wrong? And is the process mentioned in Procfile production ready on Heroku?
Thanks
Try upgrading your Django channels to 1.0.3 and whitenoise 3.3.0 the example you mentioned Is using an outdated version and some bug fixes where added to allow Daphne to serve static content with whitenoise. Alternatively you can just leverage on s3 bucket to serve your static content which is the preferred approach to serve static content with Django.
https://github.com/django/channels/issues/87
Here is my settings file.. I am getting the login page but the css and javascripts are not loading.
I gotthe whole project and i have to start working on it but i only know the basic of django so not sure why css and javascripts arenot loading. this is a very old project so it is using python 2.6.5 and django 1.3. the folder structure is also old.
# Django settings for athena.
import socket
# determine whether it's prod or dev or test/uat
if socket.gethostname().split('.')[0].lower().strip() in ('athena-dev', 'athena-test', 'lucid32'):
ATHENA_PROD_MODE = False
elif socket.gethostname().split('.')[0].lower().strip() == 'athena':
ATHENA_PROD_MODE = True
else:
raise Exception('cannot determine what mode (prod or dev) to operate in')
ATHENA_UAT_MODE = (socket.gethostname().split('.')[0].lower().strip() == 'athena-test')
if ATHENA_PROD_MODE:
DEBUG = False
else:
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (('PASystemSupport', 'pasystemsupport#apa.org'), )
MANAGERS = ADMINS
if ATHENA_PROD_MODE:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'Athena',
'USER': 'ftdbuser',
'PASSWORD': 'f0lt5xt',
'HOST': 'PIDB-SQL',
'OPTIONS': {
'driver': 'SQL Server',
'autocommit': True,
'dsn': 'PIDB-SQL',
'use_mars': True
}
}
}
elif ATHENA_UAT_MODE:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'Athena-UAT',
'USER': 'ftdbuser',
'PASSWORD': 'f0lt5xt',
'HOST': 'LANDB-DEV',
'OPTIONS': {
'driver': 'SQL Server',
'autocommit': True,
'dsn': 'LANDB-DEV',
'use_mars': True
}
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/vagrant/Athena/athena_root/athena.db',
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/New_York'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/vagrant/Athena/athena_root/athena_static/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/athena_static/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '7*f!l)^v!81vog#yzd23scp5+30db=)bub(j88nz!37nnt62mh'
# List of callables that know how to import templates from various sources.
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.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'athena_root.athena.middleware.ApplyAuthentication',
'athena_root.athena.workflow.middleware.ProdViewPermissions'
)
ROOT_URLCONF = 'athena_root.athena.urls'
TEMPLATE_DIRS = ('/vagrant/Athena/athena_root/athena_templates',
'/vagrant/Athena/athena_root/ltt/templates',
'/vagrant/Athena/athena_root/errata/templates')
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
"athena_root.athena.template_context_proc.baseTemplateContext"
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.humanize',
'athena_root.athena',
'athena_root.ltt',
'athena_root.errata'
)
EMAIL_HOST = 'mailhost.apa.org'
SERVER_EMAIL = 'PASystemsupport#apa.org'
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'django.utils.log.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True
},
'aem_db_logger': {
'level': 'DEBUG',
'class': 'athena_root.errata.log.DatabaseLoggingHandler',
'formatter': 'verbose'
}
},
'loggers': {
'django': {
'handlers': ['null'],
'propagate': True,
'level': 'INFO',
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'athena_root.errata': {
'handlers': ['aem_db_logger'],
'level': 'DEBUG',
'propagate': True
}
}
}
AUTHENTICATION_BACKENDS = ('athena_root.athena.auth.backends.AthenaAuthBackend',)
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login'
LOGOUT_URL = '/logout'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_AGE = 7257600
SESSION_SAVE_EVERY_REQUEST = False
`