Deploy django to Elastic Beanstalk in production mode using WhiteNoise - django

I am trying to deploy my django app in debug=false condition using whitenoise but i am getting 502 Bad Gateway error.I don't understand what i am doing wrong so i need help with this subject. In the log, there is this error saying:
/var/log/nginx/error.log
2021/09/13 15:06:13 [error] 2770#2770: *15675 open() "/var/app/current/static/js/bootstrap.bundle.min.js.map" failed (2: No such file or directory), client: 172.31.7.18, server: , request: "GET /static/js/bootstrap.bundle.min.js.map HTTP/1.1", host: "www.gamehunterz.com"
2021/09/13 15:06:13 [error] 2770#2770: *15675 open() "/var/app/current/static/css/bootstrap.min.css.map" failed (2: No such file or directory), client: 172.31.7.18, server: , request: "GET /static/css/bootstrap.min.css.map HTTP/1.1", host: "www.gamehunterz.com"
2021/09/13 16:02:23 [error] 4831#4831: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.37.154, server: , request: "GET /28105/albedo-and-cast-of-the-seven-godsends HTTP/1.1", upstream: "http://127.0.0.1:8000/28105/albedo-and-cast-of-the-seven-godsends", host: "www.gamehunterz.com"
2021/09/13 16:03:22 [error] 4831#4831: *18 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.7.18, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "www.gamehunterz.com"
2021/09/13 16:03:22 [error] 4831#4831: *18 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.7.18, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "www.gamehunterz.com", referrer: "https://www.gamehunterz.com/"
My django.config file:
option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: newgamehunterz.wsgi:application
aws:elasticbeanstalk:environment:proxy:staticfiles:
/static: static
My settings file like this:
import os
from pathlib import Path
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
BASE_DIR = Path(__file__).resolve().parent.parent
sentry_sdk.init(
dsn="***",
integrations=[DjangoIntegration()],
traces_sample_rate=1.0,
SECRET_KEY = 'secret-key'
DEBUG = False;
ALLOWED_HOSTS = [
'127.0.0.1', 'localhost',
'www.gamehunterz.com',
'gamehunterz.com'
]
# 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',
'games',
'authapp',
'crispy_forms',
'django.contrib.sitemaps',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
]
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 = 'newgamehunterz.urls'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['newgamehunterz/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',
'newgamehunterz.context_processors.neceseeary',
'newgamehunterz.context_processors.fav_games',
],
},
},
]
WSGI_APPLICATION = 'newgamehunterz.wsgi.application'
X_FRAME_OPTIONS = 'SAMEORIGIN'
AUTH_USER_MODEL = 'authapp.User'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '***',
'USER':'***',
'PASSWORD':'***',
'HOST':'***',
'PORT':'***',
}
}
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',
},
]
SITE_ID = 1
AUTH_USER_MODEL = 'authapp.User'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.yandex.com.tr'
EMAIL_HOST_USER = '****'
EMAIL_HOST_PASSWORD = '***'
EMAIL_PORT = ***
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = '****'
PASSWORD_RESET_TIMEOUT=360
# 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
SECURE_SSL_REDIRECT = False;
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend', # existing backend
'allauth.account.auth_backends.AuthenticationBackend',
)
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
}
}
}
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
#STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

Installing gunicorn solved the problem.

Related

File name repeating in nginx

I'm trying to setup django project to work with gunicorn and nginx server. With DEBUG=FALSE.
I see in nginx log that static word is repeated twice thus changing the path.
# settings.py
"""
Django settings for cognizance project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from pathlib import Path
import sys
# 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 = '<SECRET>'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages'
]
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 = 'cognizance.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 = 'cognizance.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
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
if sys.argv[1] != 'runserver':
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# NGINX CONF - under sites-enabled
server {
listen 80;
server_name 127.0.0.1;
location /static/ {
root /home/tejas/Desktop/cognizance;
}
location / {
proxy_pass http://127.0.0.1:8000;
}
}
# The error when I see the nginx logs
2021/04/18 17:27:05 [error] 7902#7902: *96 open() "/home/tejas/Desktop/cognizance/static/static/js/bs-init.js" failed (2: No such file or directory), client: 127.0.0.1, server: 127.0.0.1, request: "GET /static/js/bs-init.js HTTP/1.1", host: "127.0.0.1", referrer: "http://127.0.0.1/"
2021/04/18 17:27:05 [error] 7902#7902: *95 open() "/home/tejas/Desktop/cognizance/static/static/js/smoothproducts.min.js" failed (2: No such file or directory), client: 127.0.0.1, server: 127.0.0.1, request: "GET /static/js/smoothproducts.min.js HTTP/1.1", host: "127.0.0.1", referrer: "http://127.0.0.1/"
2021/04/18 17:27:05 [error] 7902#7902: *99 open() "/home/tejas/Desktop/cognizance/static/static/js/theme.js" failed (2: No such file or directory), client: 127.0.0.1, server: 127.0.0.1, request: "GET /static/js/theme.js HTTP/1.1", host: "127.0.0.1", referrer: "http://127.0.0.1/"
2021/04/18 17:27:06 [error] 7902#7902: *98 open() "/home/tejas/Desktop/cognizance/static/static/js/Simple-Slider.js" failed (2: No such file or directory), client: 127.0.0.1, server: 127.0.0.1, request: "GET /static/js/Simple-Slider.js HTTP/1.1", host: "127.0.0.1", referrer: "http://127.0.0.1/"
You can see that it requests /home/tejas/Desktop/cognizance/static/static/js/Simple-Slider.js, instead of
/home/tejas/Desktop/cognizance/static/js/Simple-Slider.js.
How do I fix it?
Project directory skeleton
I followed this tutorial to setup nginx
please ignore this, stackoverflow needs me to write few more lines of stufffff.....
Try using alias rather than root for your static files config
location /static {
alias /home/tejas/Desktop/cognizance/static/;
}
Either way you need to add /static/ to the root/alias

Django3.0: Images from database not showing-up after debug=False

After debug=False in my settings. Images from database not showing up otherwise they were. Static files are showing up real good. Even my media files were showing up before debug=False. Database has correct addresses of files but covers not showing up.
Following is the code, how I am accessing cover images.
<div class="product-top">
<img src="{{ product.cover.url }}" alt="book-image">
<h5>{{ product.title }}</h5>
</div>
my settings.py related code:
import os
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
TEMP_DIR = os.path.join(BASE_DIR, 'templates')
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'abc'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'abc#gmail.com'
EMAIL_HOST_PASSWORD = 'xyz'
EMAIL_PORT = 25
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'abc#gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
BASE_URL = '127.0.0.1:8000'
MANAGERS = (
('abc', "abc#gmail.com"),
)
ADMINS = MANAGERS
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'crispy_forms',
# myapps
'myapp',
]
AUTH_USER_MODEL = 'accounts.User'
STRIPE_SECRET_KEY = 'abc'
STRIPE_PUB_KEY = 'abc'
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',
'debug_toolbar.middleware.DebugToolbarMiddleware',
# Simplified static file serving.
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMP_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 = 'project.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 hashing (included)
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
# 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',
},
]
# 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_URL = '/static/'
STATIC_br = os.path.join(BASE_DIR,
'bookrepo/static')
STATIC_seller = os.path.join(BASE_DIR, 'seller/static')
STATICFILES_DIRS = [
STATIC_br, STATIC_seller
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
# MEDIA INFORMATION:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
as my terminal says after debug=false:
[23/Aug/2020 23:07:00] "GET /media/covers/product1.PNG HTTP/1.1" 404 11974
as my terminal says after debug=true:
[23/Aug/2020 23:25:15] "GET /media/covers/product1.PNG HTTP/1.1" 200 103898
It is worth noting that django itself does not serve static and media files when debug is false.You should use a reverse proxy like ha proxy or nginx if you are in production otherwise set debug to true for local development
Below is an example for nginx server block that serves your application, static and media files.
server {
server_name your_server_ip;
proxy_read_timeout 600s;
client_max_body_size 25M;
location /static {
alias /home/trello/static/;
}
location /media {
alias /home/trello/media/;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
}
}

why nginX server error (500) for django application?

this is the my settings.py file
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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 't8%5^$plkjtbt6bm3zngoh*5-8(e#xb_sw)9kd&!_=67)#49mk'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1.apps.App1Config',
]
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 = 'main_jntu.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'main_jntu.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/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
this is my gunicorn.conf
2020-02-12 16:59:53 +0000] [11377] [INFO] Starting gunicorn 20.0.4
[2020-02-12 16:59:53 +0000] [11377] [INFO] Listening at: unix:/home/ubuntu/js/app.sock
(11377)
[2020-02-12 16:59:53 +0000] [11377] [INFO] Using worker: sync
[2020-02-12 16:59:53 +0000] [11381] [INFO] Booting worker with pid: 11381
[2020-02-12 16:59:53 +0000] [11383] [INFO] Booting worker with pid: 11383
[2020-02-12 16:59:53 +0000] [11384] [INFO] Booting worker with pid: 11384
this is my ngix django.conf
server {
listen 80;
server_name 13.233.92.134;
location / {
include proxy_params;
proxy_pass http://unix:/home/ubuntu/js/app.sock;
}
}
i have the same servererror before when iam trying to bind with gunicorn --bind also i have got same error that server error (500). before but at that time i didnot resolved i continued for the further steps but this time its needed to solve
gunicorn --bind 0.0.0.0:8000 main_jntu.wsgi:application
(main_jntu) is my project name
at that also i have got server error (500)
please help me this out.
and thanks
i have resolved the issue is my django project is on 2.2.7 and while iam deploying on aws i used latest version so i got the server error
note:use only the version of django you used while developing project and use same version while deploying the project

Django application on EC2 and RDS ( Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?)

I have created an EC2 instance on AWS and deployed my django application on it.
Also created RDS postgres database on AWS. Whenever I access my public ip, I get the following error,
OperationalError at /
could not connect to server: Connection refused Is the server running
on host "localhost" (127.0.0.1) and accepting TCP/IP connections on
port 5432?
Both EC2 and RDS instances are connected. Verified by following,
Connected RDS postgres using pgadmin4 on my local PC.
Created supersuser on ec2 console and it populated the postgres.
Nginx configuration:
server {
listen 80;
server_name 18.218.45.241;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/ubuntu/Crowdsocial_project;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/ubuntu/Crowdsocial_project/crowdsocial.sock;
}
}
Gunicorn configuration:
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/Crowdsocial_project
ExecStart=/home/ubuntu/Crowdsocial_project/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/Crowdsocial_project/crowdsocial.sock main.wsgi:application
[Install]
WantedBy=multi-user.target
EC2 Security group:
RDS Security group:
Settings.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
# 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 = 'secret'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['18.218.45.241']
DATE_INPUT_FORMATS= ['%Y-%m-%d',]
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example#gmail.com'
EMAIL_HOST_PASSWORD = 'pass'
EMAIL_PORT = 587
# Application definition
INSTALLED_APPS = [
'users.apps.UsersConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap_modal_forms',
'main',
'first_app',
'campaign',
'invoice',
'taggit',
'corsheaders',
'taggit_selectize',
'rest_framework',
'django_filters',
'django_extensions',
'shop',
'search',
'cart',
'orders',
'widget_tweaks',
'billing',
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
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',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']
CORS_ORIGIN_ALLOW_ALL = True
ROOT_URLCONF = 'main.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.media',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'main.wsgi.application'
AUTH_USER_MODEL = 'users.CustomUser'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'name',
'USER': 'user',
'PASSWORD': 'pass',
'HOST': 'crowdsocial-postgres.c9sefqws77mc.us-east-2.rds.amazonaws.com',
'PORT': '5432',
}
}
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
LOGIN_URL = 'users:login'
# LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'first_app:home'
Answer
I Was facing the same problem. I reboot EC2 Machine and it works for me.
Try it maybe it will work for you.
Go to security group
go to inbound
click on edit and add rule
type:postgresql , source:anywhere
and save , It has worked for me.

Django compressor and manage.py compress problems

My problem: When debug=true in settings.py django compress works just fine, takes all the js concatenates everything and minifies, when debug-false is basically useless: if i set COMPRESS_ENABLED = True (default when debug=false) i get a 500 error, but don't really know what's going on:
It:mysite italo$ ./manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
August 25, 2016 - 17:37:47
Django version 1.10, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[25/Aug/2016 17:37:51] "GET / HTTP/1.1" 500 6098
[25/Aug/2016 17:37:51] "GET /static/scss/app.css HTTP/1.1" 304 0
[25/Aug/2016 17:37:51] "GET /static/CACHE/js/f6979994c378.js HTTP/1.1" 200 3524
[25/Aug/2016 17:37:51] "GET /static/CACHE/js/029dc704a0f3.js HTTP/1.1" 200 3788
[25/Aug/2016 17:37:51] "GET /static/CACHE/js/bd8a8faf4632.js HTTP/1.1" 200 135985
[25/Aug/2016 17:37:51] "GET /static/CACHE/js/50721ef0285b.js HTTP/1.1" 200 98
[25/Aug/2016 17:37:51] "GET /static/CACHE/js/2f9428d5f621.js HTTP/1.1" 200 138405
looks like i get several javascript files loaded (apparently not concatenating at all) but the css files are minified... my solution used to be to set COMPRESS_ENABLED = False on production and then write a script to do:
1) collectstatic
2) compress --force (because ompressor is disabled, i tried to enable it temporary before running runserver and using just compress but i get the same results)
3) runserver
What i get is separate files and they're not minified, I don't get any error, but having different non minified js files is pretty much useless IMHO.
i tried
using ALLOWED_HOSTS = ['*']
updating to the latest version in compressor
disabling whitenoise
ALLOWED_HOSTS = ['*']
disabling css processor (even though sass compilation is ok i just don't get concatenation when debug=false)
this is suggested in many posts but doesn't work.
My first question: how do i fix this?
I'm clueless and at this point my second question would be if there's a working alternative to django-compressor.
import os
import dj_database_url
import compressor
import socket
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT_PATH = os.path.dirname(__file__)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
if os.environ['PRODUCTION'] == '1':
DEBUG = False
# ALLOWED_HOSTS = ['itmandar.herokuapp.com']
else:
DEBUG = True
# ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
print 'DEBUG', DEBUG, 'assuming we\'re not in production'
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'myresume.apps.MyresumeConfig',
'sass_processor',
'django_markup',
'compressor',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
if DEBUG:
INSTALLED_APPS += ['template_repl']
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'myresume/templates/')],
'APP_DIRS': True,
'OPTIONS': {
'debug' : DEBUG,
'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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mysite',
'USER': 'it',
'PASSWORD': os.environ['DB_KEY'],
'HOST': 'localhost',
'PORT': '',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/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/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
# django filepicker
FILEPICKER_API_KEY = os.environ['FILEPICKER_API_KEY']
FILEPICKER_API_SECRET = os.environ['FILEPICKER_API_SECRET']
CWD = os.getcwd()
MEDIA_ROOT = os.path.join(CWD, 'media')
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
# media urls
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]
# sass processor settings
# SASS_PROCESSOR_ROOT = os.path.join(ROOT_PATH, 'static')
SASS_PRECISION = 8
SASS_PROCESSOR_ENABLED = DEBUG
COMPRESS_JS_FILTERS = ['compressor.filters.jsmin.JSMinFilter']
COMPRESS_OFFLINE = not DEBUG
if DEBUG:
#sass processor
SASS_OUTPUT_STYLE = 'nested'
else:
#sass processor
SASS_OUTPUT_STYLE = 'compressed'
since the problem is related to the fact that django is not serving static files when debug=false, i decided to use this solution http://www.kennethreitz.org/essays/introducing-dj-static
it's a module called dj-static
the problem is now solved.