Unable to get Images from AWS-S3 bucket in django-app? - django

I'm using AWS-S3 to store my users' profile images. I've repeated this process 7-8 times but when I open my app on local machine(I've not deployed it yet) the user profile images aren't there and it shows the alt='not found' in place of images.
I've made a user in IAM and a bucket in S3 same as in this tutorial nearly 5 times but there's no way I'm getting the images.
Also when I right click on any image in my app and go into the image location I'm getting this in my browser.
This XML file does not appear to have any style information associated with it. The document tree is shown below.
AccessDeniedAccess Denied6683BC64F8FCAB0CE2foYctY9f7GMW+VI64vr3rRfMPrXXGfscryk3Eqo7meEtenXCLSa4kGYnQBJV6qDG9AdBVVgR8=
Here's my settings.py file
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
MEDIA_DIR = os.path.join(BASE_DIR,'myblog/media')
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'blogapp.apps.BlogappConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'storages'
]
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 = 'myblog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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 = 'myblog.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
'OPTIONS':{
'max_similarity': 1,
}
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'blogapp/static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = MEDIA_DIR
LOGIN_REDIRECT_URL = 'blogapp:post_list'
LOGIN_URL = 'login'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS')
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 = 'djangoblogapp'
AWS_LOCATION = 'static'
AWS_QUERYSTRING_AUTH = False
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
In absence of S3 the app works fine but using AWS the images aren't getting loaded. I've downloaded boto3 and django-storages and using django 2.2.

Sounds like a CORS issue from the S3 side, see the docs from AWS. You will need to have a CORS configuration for the bucket to allow non-S3-console sites to see the files (you are getting a fairly generic XML empty response).
You will need to go to the permissions tab for your bucket, then CORS configuration, and enter something like the policies from the link, eg a very basic one that should allow you to use your images as you want would look like:
<CORSConfiguration>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
</CORSRule>
</CORSConfiguration>
but if you need something more sophisticated/limiting then the docs there are pretty good.

Related

Hosting Static Files on Amazon Web Services > Amazon Bucket - Django - PNG - CSS files

I need to host my static files on AWS in order to sort out some problems I have been having with my Django website. I have been trying to solve this on and off for about a year now while finishing up the rest of the website but now it is the last thing to do and I can't put it off any longer. I have looked at the documentation and looked at so many videos with no luck. Below is everything I have including code and my bucket file configuration that pertains to this problem. Everything that I currently have running should be hosting all my static files on my Amazon Bucket, however, it isn't. I'm not getting an error but when I 'inspect' on google they are all being hosted locally. I have followed so many tutorials and started from scratch so many times and nothing is seeming to work. Thank You so much in advance.What is wrong with the configuration below? Is MEDIA_URL affecting it?
P.S. = The gallery folder I have in my bucket is for images that users upload and those images are successfully being hosted on AWS and working fine it's just the static. This means the connection to the bucket is working fine.
import django_heroku
from pathlib import Path
import os
from django_quill import quill
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ROOT_DIR = os.path.dirname(BASE_DIR)
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
#MEDIA_ROOT = os.path.join(BAS_DIR, 'media')
TIME_INPUT_FORMATS = ['%I:%M %p',]
#Media_URL = '/signup/front_page/sheets/'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'HERE BUT NOT SHOWN'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
#ADMIN_USERNAME = 'HERE BUT NOT SHOWN'
#ADMIN_PASSWORD = 'HERE BUT NOT SHOWN'
#AUTHENTICATION_BACKENDS = [
# 'django.contrib.auth.backends.ModelBackend',
# 'config.backends.SettingsBackend',
#]
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',
'django_quill',
'tinymce',
'ckeditor',
'boto3',
#'django_extensions',
'storages',
#'django-storages',
'django_filters',
]
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 = 'inspect_list.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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 = 'inspect_list.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/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/3.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',
},
]
AWS_ACCESS_KEY_ID = 'HERE BUT NOT SHOWN'
AWS_SECRET_ACCESS_KEY = 'HERE BUT NOT SHOWN'
AWS_STORAGE_BUCKET_NAME = 'name1234'
AWS_S3_CUSTOM_DOMAIN = 'name1234.s3.amazonaws.com'
AWS_LOCATION = 'static'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = 'https://name1234.s3.amazonaws.com/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
#AWS_S3_FILE_OVERWRITE = False
#AWS_DEFAULT_ACL = None
#DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
#STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
#STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
#STATIC_URL = '/static/'
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Cancun'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
AUTH_USER_MODEL = 'my_app.CustomUser'
LOGIN_REDIRECT_URL = 'front_page'
LOGOUT_REDIRECT_URL = 'login'
django_heroku.settings(locals())
The question is not clear. You're asking about static resources but the code you have shared is of Django and Heroku? How come Python / Django can be static? Which URL you're using to load your website? If you're using localhost then it can't be from S3 and if it's s3 URL then it can't be local.
Another problem I can guess is hardcoded wrong paths in static assets. You have to make all your paths "relative" for static S3 website hosting to work.
Another solution is to use CloudFront in front of S3 to route dynamic contents of your website to your Django application. You can host your Django app on Heruko or EC2 or ECS/EKS, etc. So 1 origin for S3 and 2nd origin for your python code.

Django Admin raise 500 error in production Heroku

I know this question was raised multiple times, but wasn't able to solve the problem.
Here is my problem: my Django-React app is deployed on Heroku and works great (very simple app). I would like know to access the /admin part of my app, but I get a 500 Internal Server Error.
The error appears locally and in Heroku.
The DEBUG is False, and unfortunately I can't get the logs to work, neither in Heroku nor locally :(
Here is my settings.py:
from pathlib import Path
import django_heroku
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxx'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['vmbf.herokuapp.com', '127.0.0.1', 'localhost']
ADMINS = [('username', 'emailaddress')]
MANAGERS = ADMINSEMAIL_HOST = 'host'
SEND_BROKEN_LINK_EMAILS=True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'emailaddress'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
SERVER_EMAIL = EMAIL_HOST_USER
# 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',
'students',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'corsheaders.middleware.CorsMiddleware',
'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 = 'django_react_proj.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'students-fe/build')],
'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 = 'django_react_proj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 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
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
django_heroku.settings(locals())
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOWED_ORIGINS = (
'https://vmbf.herokuapp.com',
)
CSRF_TRUSTED_ORIGINS = [
'vmbf.herokuapp.com',
]
STATIC_ROOT = os.path.join(BASE_DIR,'students-fe', 'build', 'static')
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
And here is how my folder looks like:
Folder structure
Feel free to ask me more code, I'm new to Django / React therefore I'm not sure what I should share here or not.
So I found out my problem.
It was not related to PostgreSQL, but thank you #Chris to pointing that out, it's better development methodology for myself.
The problem was related to how I managed the Static Files in my settings.py
I didn't understood how STATIC_ROOT works, I understood the other way around. After reflecting on it here is what I did:
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')
My files will be served from this staticfiles directories.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'students-fe','build','static'),
]
But it has to include my react app that is in students-fe/build/static folder.
On top of that, when deploying to Heroku, it is necessary to add the buildpacks, which I did but not in the correct order.
First I needed to add python (for Django):
heroku buildpacks:set heroku/python
and then saying that before that it needs to install nodejs (for React):
heroku buildpacks:add --index 1 heroku/nodejs
Like this Heroku will first do a npm run build before the python manage.py collecstatic that is needed to move the static files into the staticfiles folder.
Hope it can help others.
Thanks to all for your answers.

Django site not updated

I got my django app configured with AWS S3 and all the media files are hooked up correctly. When I post a new article, the media files are stored in S3 and everything seems to work fine. After about 5 hours, I checked the site and it was back to a time frame where the article was not posted. This means it went back in time and got regressed to an earlier code? I don't know what is happening, and why after many days of testing it ALWAYS goes back to that one stage. Any advice?
Settings file:
DEBUG = False
ALLOWED_HOSTS = ['XXX.heroku', '127.0.0.1', 'localhost', '.XXX.com, '.XXX']
# Application definition
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',
'ckeditor_uploader',
'django_cleanup',
'storages',
]
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 = 'analyst.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 = 'analyst.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.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/3.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',
},
]
CKEDITOR_CONFIGS = {
"default": {
"removePlugins": "stylesheetparser",
}
}
# Internationalization
# https://docs.djangoproject.com/en/3.0/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.0/howto/static-files/
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/'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'XXX#gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST_PASSWORD = 'XXX'
EMAIL_PORT = 587
AWS_ACCESS_KEY_ID = 'XXX'
AWS_SECRET_ACCESS_KEY = 'XXX'
AWS_STORAGE_BUCKET_NAME = 'XXX'
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = 'public-read'
DEFAULT_FILE_STORAGE = 'analyst.aws.storage_backends.MediaStorage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_QUERYSTRING_AUTH = False
CKEDITOR_UPLOAD_PATH = 'media'
AWS_S3_REGION = 'ap-southeast-1'

Facing Issue With Django Machina Templates

I am Working on Rating Professor Website Using Django Framework.So That's Why I am Using Machina Forum But Facing Templates Issue In Settings .Loaders Are Not Working 'APP_DIRS': True, But When I Change 'APP_DIRS': False ,And Add MACHINA_MAIN_TEMPLATE_DIR To Templates Directory Machina Website Forum Works Fine But My Actual Website Goes Off Because of No Templates Exits Error.
Question is That Can i Use Both Machina And My Template Directory at Same time And how ?
If I add Machina Templates to Pycharm Project Templates and Make them as Templates then it's Work Or not ?
There is Only Issue With Machina Templates Everything is Working Excellent . I Just Wanted Both Templates to Work On My Website .
Setting.py
import os
from machina import MACHINA_MAIN_TEMPLATE_DIR
from machina import MACHINA_MAIN_STATIC_DIR
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'SECRET_KEY'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'users.apps.UsersConfig',
'crispy_forms',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'djangoproject.apps.DjangoprojectConfig',
'axes',
'widget_tweaks',
'pinax.comments',
'sslserver',
'simple_history',
'admin_honeypot',
'captcha',
# Machina dependencies:
'mptt',
'haystack',
# Machina apps:
'machina',
'machina.apps.forum',
'machina.apps.forum_conversation',
'machina.apps.forum_conversation.forum_attachments',
'machina.apps.forum_conversation.forum_polls',
'machina.apps.forum_feeds',
'machina.apps.forum_moderation',
'machina.apps.forum_search',
'machina.apps.forum_tracking',
'machina.apps.forum_member',
'machina.apps.forum_permission',
]
AUTHENTICATION_BACKENDS = [
# AxesBackend should be the first backend in the AUTHENTICATION_BACKENDS list.
'axes.backends.AxesBackend',
# Django ModelBackend is the default authentication backend.
'django.contrib.auth.backends.ModelBackend',
]
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',
'axes.middleware.AxesMiddleware',
'simple_history.middleware.HistoryRequestMiddleware',
'machina.apps.forum_permission.middleware.ForumPermissionMiddleware',
]
SILENCED_SYSTEM_CHECKS = ['axes.W003']
ROOT_URLCONF = 'review.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'djangoproject/../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',
'machina.core.context_processors.metadata',
],
},
},
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
'machina_attachments': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/tmp',
}
}
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
},
}
WSGI_APPLICATION = 'review.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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.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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
MACHINA_MAIN_STATIC_DIR,
]
STATICFILES_DIRS = (
# ...
MACHINA_MAIN_STATIC_DIR,
)
MACHINA_DEFAULT_AUTHENTICATED_USER_FORUM_PERMISSIONS = [
'can_see_forum',
'can_read_forum',
'can_start_new_topics',
'can_reply_to_topics',
'can_edit_own_posts',
'can_post_without_approval',
'can_create_polls',
'can_vote_in_polls',
'can_download_file',
]
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SETTINGS_PATH = os.path.realpath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, r'C:\Users\Windows 10\PycharmProjects\review\templates\djangoproject'),
)
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
AXES_ENABLED = False
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_REDIRECT_URL='blog-home'
LOGIN_URL='login'
MAX_UPLOAD_SIZE = "5242880"
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'SECRET'
EMAIL_HOST_PASSWORD = 'SECRET'

Heroku: images don't show after some time

I've a Django APP hosted on Heroku.
I upload some images within the admin panel, so the show in my site. First minutes/hours after upload they show fine.
However, after a few hours they don't show anymore. I've to upload them again within the admin panel for them to show correctly.
When in the HTML when no image appear:
<img class="my_image_medium" src="/media/category/Artboard_1_PNG.png" alt="Stickers">
HTML with image re-uploaded:
<img class="my_image_medium" src="/media/category/Artboard_1_PNG.png" alt="Stickers">
Django APP 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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^_67&#r+(c+%pu&n+a%&dmxql^i^_$0f69)mnhf#)zq-rbxe9z'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', 'stickers-gallito-app.herokuapp.com',
'stickersgallito.pe', 'www.stickersgallito.pe']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'shop',
'search_app',
'cart',
'stripe',
'order',
'crispy_forms',
'embed_video',
]
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 = 'stickers_gallito.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'shop', 'templates/'),
os.path.join(BASE_DIR, 'search_app', 'templates/'),
os.path.join(BASE_DIR, 'cart', 'templates/'),
os.path.join(BASE_DIR, 'order', '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',
'shop.context_processor.menu_links',
'shop.context_processor.has_shop',
# 'cart.context_processor.current_time',
'cart.context_processor.cart_items_counter'
],
},
},
]
WSGI_APPLICATION = 'stickers_gallito.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'd39a83vqn3afdj',
'USER': 'u9qchlpdl8pbao',
'PASSWORD': 'pcf1d926adfd169634371480b03c270d7da7b9033c81210482571f1a8d0ad689b',
'HOST': 'ec2-3-93-140-235.compute-1.amazonaws.com',
'PORT': '5432',
# 'OPTIONS': {
# 'sslmodule': 'required'
# }
}
}
# add this
# import dj_database_url
# db_from_env = dj_database_url.config()
# DATABASES['default'].update(db_from_env)
# Password validation
# https://docs.djangoproject.com/en/2.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/2.1/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.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
CRISPY_TEMPLATE_PACK = 'bootstrap4'
### Culqui Settings ###
CULQI_PUBLISHABLE_KEY = 'pk_test_d4d1nYriXvMV0YKk'
CULQI_SECRET_KEY = 'sk_test_sOlYqSB5PDAkwQuZ'
You are storing your uploaded images on the local filesystem. You cannot do that in Heroku.
Heroku instances are ephemeral, and do not share filesystems between them. Whenever you deploy, or launch a new instance by scaling up, it will not have any of your uploaded files.
You must store them somewhere more permanent. S3 is a good choice; there are plenty of third-party Django file storage libraries available that will do this for you.
This is because heroku nodes are not persistent. Meaning everytime your free node shuts down, it actually gets deleted and a new instance gets started when you access your application again.
The solution is actually to use some other hoster to store your media files. Amazon S3 or a simple FTP Server for example.
Check these links for further information:
Using AWS S3 to Store Static Assets and File Uploads
Heroku Help: Why are my file uploads missing/deleted?