Server Error After Setting DEBUG=False Django - python

I keep getting Sever error- 500 after setting DEBUG=True both on localhost and the hosted version and I don't know the cause of the error.
Here are some my code in my settings.py file
import os
from pathlib import Path
from decouple import config
import django_heroku
import dj_database_url
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = str(os.getenv('SECRET_KEY'))
DEBUG = config("DEBUG", default=False, cast=bool)
ALLOWED_HOSTS = ["127.0.0.1", "localhost", "cv-build.onrender.com"]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"cloudinary_storage",
"cloudinary",
'app',
]
MEDIA_URL = "/cv-build/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATIC_URL = "/static/"
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')]
STATIC_ROOT = os.path.join(BASE_DIR, "app/static")
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
DEFAULT_FILE_STORAGE = "cloudinary_storage.storage.MediaCloudinaryStorage"
CLOUDINARY_STORAGE = {
"CLOUD_NAME": config("CLOUDINARY_CLOUD_NAME"),
"API_KEY": config("CLOUDINARY_API_KEY"),
"API_SECRET": config("CLOUDINARY_API_SECRET"),
}
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
I've tried to sort it out by checking the Allowed Host, static settings and all but it is the same result.
Thanks.

Related

Django - Not Found The requested resource was not found on this server on Production

I was trying to deploy my Django project on Render . Everything works fine except for the media files. I can't figure out the issue here.
I have added the followings into my settings.py:
DEBUG=False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]
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',
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
]
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [
BASE_DIR / "static"
]
MEDIA_URL = '/contents/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/contents/')
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage"
urls.py
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
I have created a Post (using models) before deploying. It had an image located a ./static/contents/Screenshot_334.png After deploying this image is accessible at https://someusername.onrender.com/static/contents/Screenshot_334.png . But if I create a new post from the deployed site I get a 404 error. The site doesn't cause any issue while its in the development mode.
Here's a portion of LOGS from Render:
https://someusername.onrender.com/static/contents/Screenshot_334.png (created while development) is accessible but https://someusername.onrender.com/static/contents/Screenshot_1.png (created post-production) is inaccessible. Also, static files (css, js) working fine.
I checked all the files and directories using the following piece of code:
res = []
for path, subdirs, files in os.walk('./'):
for name in files:
res.append(os.path.join(path, name))
Screenshot_334.png and Screenshot_1.png both are in the same directory
I also tried switching MEDIA_URL and MEDIA_ROOT to 'contents', 'contents/', 'static/contents/' and all the possible variations.
UPDATE:
I have found a workaround since I couldn't figure it out myself. I have mapped media to the urls.py and used FileResponse
Here's how views.py looks:
from django.http import FileResponse
def media(request, path:None):
img = open('./contents/'+path, 'rb')
response = FileResponse(img)
return response
I'm aware this might cause security issues but I think it won't do me any harm since it is a project just for learning.
Add whitenoise in your installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'whitenoise',
'accounts',
]
then add whitenoise.middleware.WhiteNoiseMiddleware in your middleware right after the first line.
try configring the static files as below in your settings.py
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [
BASE_DIR / "static"
]
MEDIA_URL = 'contents/'
MEDIA_ROOT = BASE_DIR / 'static/contents'
edit your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path(....)
]
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT
)

Django AWS S3 Files Not Showing Up on Site

When I check the page source, the link is linking to the correct AWS links but no images/css or media files are showing up. The bucket policy and CORS are configured as it should according to the tutorials I've followed. The bucket has the mdeia and static folders inserted as well.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
(os.path.join(BASE_DIR, 'static')),
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
AWS_ACCESS_KEY_ID = 'XXX'
AWS_SECRET_ACCESS_KEY = 'XXX'
AWS_STORAGE_BUCKET_NAME = 'XXX'
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog.apps.BlogConfig',
'crispy_forms',
'ckeditor',
'django_cleanup',
'storages',
]
What you've got is incomplete. You need something like this:
Create aws folder next to your settings.py with __init__.py and the following files:
conf.py:
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = {BUCKET_NAME}
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_LOCATION = 'static'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
DEFAULT_FILE_STORAGE = '{appname}.settings.aws.storage_backends.MediaStorage'
storage_backends.py:
from storages.backends.s3boto3 import S3Boto3Storage
class MediaStorage(S3Boto3Storage):
location = 'media'
file_overwrite = False
then import it into your settings.py/production settings file:
from .aws.conf import *

DoesNotExist at /admin/login/ Site matching query does not exist

at local when i accessed localhost:8000/admin, it worked....!!! but when i access https://realmento.herokuapp.com/admin/login/?next=/admin/ , i get message DoesNotExist at /admin/login/
Site matching query does not exist. i have deployed my project to heroku...
this is my setting.py :
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
location = lambda x: os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', x)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# 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',
'index',
'category',
'products',
'allauth',
'allauth.account',
'allauth.socialaccount',
# ... include the providers you want to enable:
'allauth.socialaccount.providers.bitly',
'allauth.socialaccount.providers.dropbox',
'allauth.socialaccount.providers.github',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.facebook',
)
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',
'solid_i18n.middleware.SolidLocaleMiddleware',
)
SITE_ID = 1
SITE_ID = 2
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
"allauth.account.context_processors.account",
"allauth.socialaccount.context_processors.socialaccount",
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.i18n",
'realmento.context_processors.solid_i18n',
)
# default language, it will be used, if django can't recognize user's language
LANGUAGE_CODE = 'en'
# supported languages
LANGUAGES = (
('en', 'English'),
('ko', 'Korean'),
)
USE_I18N = True
LOCALE_PATHS = (
location('locale'),
)
CACHES = {
'default': {
'BACKEND':'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION':'127.0.0.1:8000',
}
}
###############################################################
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR,'templates'), os.path.join(BASE_DIR,'templates', 'allauth'))
#################################################################
ROOT_URLCONF = 'realmento.urls'
WSGI_APPLICATION = 'realmento.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
TIME_ZONE = 'UTC'
USE_L10N = True
USE_TZ = True
ADMINS = (('HOANGTHINH', 'rongbay054#gmail.com'), )
EMAIL_SUBJECT_PREFIX = "[Translation] "
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'hoangthinh2641995#gmail.com'
EMAIL_HOST_PASSWORD = '*************'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
LOGIN_REDIRECT_URL = '/realmento/intro'
LOGOUT_URL = "/accounts/login/"
SOLID_I18N_USE_REDIRECTS = False
SOLID_I18N_HANDLE_DEFAULT_PREFIX = False
SOLID_I18N_DEFAULT_PREFIX_REDIRECT = False
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'realmento',
'USER': 'postgres',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '5432',
}
}
# DATABASE_URL=postgres:///postgres:root#localhost/realmento
DATABASES['default'] = dj_database_url.config(default = 'postgres://postgres:root#localhost/realmento')
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
So what's the problem? Thanks a lot for your help!
Remove 'django.contrib.sites' from your settings file.
It worked for me.
That's becaue /admin/login/ is not there, try opening
https://realmento.herokuapp.com/admin/ only.
or try opening
localhost:8000/admin/login/?next=/admin/
and see if it opens or not.
Did you run python manage.py collectstatic This will copy all files from your static folders into the STATIC_ROOT directory.

Set STATIC_URL on Heroku but getting ImproperlyConfigured at /admin/login/

Getting:
ImproperlyConfigured at /admin/login/ You're using the staticfiles app
without having set the required STATIC_URL setting.
after I deployed the Django app to Heroku:
https://rtd2015.herokuapp.com/admin/
I'm also getting a 404 on the root URL: rtd2015.herokuapp.com.
Thanks
base.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from os import environ
import dj_database_url
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!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, '../templates/'),
)
ALLOWED_HOSTS = ['.herokuapp.com', '.researchthroughdesign.org',]
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'gunicorn',
'markdown_deux',
'storages',
'site_2015',
)
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 = 'app.urls'
WSGI_APPLICATION = 'app.wsgi.application'
DATABASES = {}
DATABASES['default'] = dj_database_url.config()
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
MARKDOWN_DEUX_STYLES = {
"STYLE": {
"extras": {
"code-friendly": None,
},
"safe_mode": False,
},
}
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder'
)
production.py
from base import *
AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
AWS_STORAGE_BUCKET_NAME = 'rtd2015'
STATICFILES_STORAGE = 'app.settings.s3utils.StaticRootS3BotoStorage'
DEFAULT_FILE_STORAGE = 'app.settings.s3utils.MediaRootS3BotoStorage'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '../../srv/assets'),
)
STATIC_ROOT = 'http://rtd2015.s3.amazonaws.com/static/'
STATIC_URL = 'http://rtd2015.s3.amazonaws.com/static/'
MEDIA_ROOT = 'http://rtd2015.s3.amazonaws.com/media/'
MEDIA_URL = 'http://rtd2015.s3.amazonaws.com/media/'

Django admin template is broken in production

I'm working with django, and trying to deploy my app to heroku.
All is working without any problems in local (even with DEBUG=False), but when deployed to heroku, the admin template doesn't display when DEBUG=False.
I followed theses instructions to configure my settings.py : https://devcenter.heroku.com/articles/django-assets
And here is my Procfile :
web: gunicorn bourse_logements.wsgi -b 0.0.0.0:$PORT
Feel free to ask if yu need some parts of my settings.py, I will paste them
Any help would be appreciated
EDIT :
Here is my settings.py :
https://gist.github.com/e-goz/62f812ab1fa8f8268f94
Are you sure you didn't .gitignore the templates folder?
* Add This line to your setting.py*
ADMIN_MEDIA_PREFIX = '/static/admin/'
you have to also copy all admin CSS and JavaScript to your static path(within static folder)
like static/admin/"you staticfiles"
You can try This setting as per your configuration on setting.py.
from unipath import Path
PROJECT_DIR = Path(__file__).ancestor(3)
PROJECT_ROOT = Path(__file__).ancestor(2)
sys.path.insert(0, Path(PROJECT_ROOT, 'apps'))
MEDIA_ROOT = PROJECT_DIR.child("media")
MEDIA_URL = '/media/'
STATIC_ROOT = PROJECT_DIR.child("collected_static")
STATIC_URL = '/static/'
STATICFILES_DIRS = (
PROJECT_DIR.child("static"),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
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',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
TEMPLATE_DIRS = (
Path(PROJECT_ROOT, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.flatpages',
)
# Heroku specific settings
import dj_database_url
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')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# You can also try in your url.py
if settings.LOCAL_DEV:
baseurlregex = r'^media/(?P<path>.*)$'
urlpatterns += patterns('',
(baseurlregex, 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

Categories

Resources