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 *
Related
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.
Intro: I have made my application in Django I am trying to get my static and media files hosted in aws s3. My Django project is on AWS Lambda and AWS Api gateway using Zappa. below is my settings.py
AWS_DEFAULT_ACL = None
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
DEFAULT_FILE_STORAGE = 'aws_storage_classes.MediaStorage'
AWS_ACCESS_KEY_ID = os.getenv("ACCESS_KEY")
AWS_SECRET_ACCESS_KEY = os.getenv("ACCESS_SECRET_KEY")
AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME")
STATICFILES_STORAGE = 'aws_storage_classes.StaticStorage'
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_S3_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME
STATIC_URL = 'https://%s.static/' % AWS_S3_DOMAIN
MEDIA_URL = 'https://%s.media/' % AWS_S3_DOMAIN
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I then created a file in my project folder the same as my manage.py called aws_storage_classes.py
Below are the contents of my file aws_storage_classes.py
from storages.backends.s3boto3 import S3Boto3Storage
class StaticStorage(S3Boto3Storage):
location = 'static'
class MediaStorage(S3Boto3Storage):
location = 'media'
Below are my urls
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Also in my settings.py
DEBUG = False
When I do python manage.py collectstatic all the staticfiles are downloaded and I don't get any errors. But when go on admin page the static files are not uploaded. See images below
Below is the image of my S3 bucket
Below is what is inside the static folder
Static files not loading
<link rel="stylesheet" type="text/css" href="https://<bucketname>.s3.amazonaws.com/static/style.css?AWSAccessKeyId=AKIAJHJGHJGJGJGJJGJGJMHIFQ&Signature=yfS3%2BvA0q15aUxw7OBySuQWZfjg%3D&x-amz-security-token=FQoGZXIvYXdgljdaksfgdjsgfkjertert;hre;thtires=151232173">
Updated settings.py
AWS_DEFAULT_ACL = None
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
DEFAULT_FILE_STORAGE = 'aws_storage_classes.MediaStorage'
AWS_ACCESS_KEY_ID = os.getenv("ACCESS_KEY")
AWS_SECRET_ACCESS_KEY = os.getenv("ACCESS_SECRET_KEY")
AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME")
STATICFILES_STORAGE = 'aws_storage_classes.StaticStorage'
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_S3_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME
STATIC_URL = 'https://%s.static/' % AWS_S3_DOMAIN
MEDIA_URL = 'https://%s.media/' % AWS_S3_DOMAIN
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Below is the link after adding ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
<link rel="stylesheet" type="text/css" href="https://django-static-media.s3.amazonaws.com/static/style.css?AWSAccessKeyId=AKIAGGGGGGGGGMHIFQ&Signature=6gFQTsOSDFSDFA%3D&x-amz-security-token=FQoGZvwbJhd9amp;Expires=1549168642">
The issue is your url should be /static/admin/style.css/.... to fix this add the following to your settings.py file.
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
filebrowser
127.0.0.1:8000/admin/filebrowser/browse/?
upload file success
image url href: href="media/uploads/chrysanthemum.jpg"
but the url is wrong.
"/media/uploads/chrysanthemum.jpg"
this url is right.
"_versions/chrysanthemum_admin_thumbnail.jpg">
is wrong
"/media/_versions/chrysanthemum_admin_thumbnail.jpg">
is right.
settings.py:
INSTALLED_APPS = [
'grappelli',
'filebrowser',
'django.contrib.admin',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
("images",os.path.join(STATIC_ROOT, 'images').replace('\\', '/')),
("css", os.path.join(STATIC_ROOT, 'css').replace('\\', '/')),
("js", os.path.join(STATIC_ROOT, 'js').replace('\\', '/')),
)
ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/"
site.directory = "media/uploads/"
site.storage.location = BASE_DIR
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\','/')
directory:
settings.py
remove two rows
site.directory = "media/uploads/"
site.storage.location = BASE_DIR
Because MEDIA_URL and MEDIA_ROOT were setted up. And Filebrowser is right
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.
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/'