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
Related
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.
Running an app in Django. When Debug=True it all works fine. When Debug=False most of the app works fine except from a few static files, from what I was able to understand js files.
I run already python manage.py collectstatic and the css of the templates work, so the processs seems to have been succesful. Still though, a few JS files don't get loaded and this is messing up my admin panel.
This is the terminal error for the production environment (debug=False)
[21/Feb/2021 17:38:00] "GET /admin/ HTTP/1.1" 200 7803
[21/Feb/2021 17:38:00] "GET /static/admin/css/dashboard.css HTTP/1.1" 200 380
[21/Feb/2021 17:38:00] "GET /static/admin/img/icon-changelink.svg HTTP/1.1" 200 380
[21/Feb/2021 17:38:09] "GET /admin/amonthatatime/post/ HTTP/1.1" 200 9867
[21/Feb/2021 17:38:09] "GET /admin/jsi18n/ HTTP/1.1" 200 3187
[21/Feb/2021 17:38:11] "GET /admin/amonthatatime/post/1/change/ HTTP/1.1" 200 35171
[21/Feb/2021 17:38:11] "GET /admin/jsi18n/ HTTP/1.1" 200 3187
[21/Feb/2021 17:38:11] "GET /summernote/editor/id_medley/ HTTP/1.1" 200 7148
[21/Feb/2021 17:38:11] "GET /summernote/editor/id_whatsapp/ HTTP/1.1" 200 7154
[21/Feb/2021 17:38:11] "GET /static/summernote/lang/summernote-en-US.min.js?_=1613929091381 HTTP/1.1" 200 27
[21/Feb/2021 17:38:11] "GET /static/summernote/lang/summernote-en-US.min.js?_=1613929091408 HTTP/1.1" 200 27
This is my settings.py
from pathlib import Path
from django.conf import settings
from django.conf.urls.static import static
import os
import psycopg2
import dj_database_url
import cloudinary
# 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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'giaggi.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'amonthatatime.apps.AmonthatatimeConfig',
'django_summernote',
'cloudinary'
]
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 = 'giaggi.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 = 'giaggi.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.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/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_URL = '/amonthatatime/static/amonthatatime/images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'amonthatatime/static/amonthatatime/images/')
X_FRAME_OPTIONS = 'SAMEORIGIN'
#SECURE_SSL_REDIRECT=False
#SESSION_COOKIE_SECURE=False
#CSRF_COOKIE_SECURE=False
# Configure Django App for Heroku.
#import django_on_heroku
#django_on_heroku.settings(locals())
I have also faced the same issue and run collectstatic as well.
In my case, it improved not fully, but also I have found another ajax script and bootstrap bothered my CSS. (Just FYI, it was
https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js)
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
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.
I am almost done building my website but while creating an autogenerating slug in Django admin, I found it to be unresponsive. When i looked at the console of my browser i see a lot of JS error warnings. The nginx is correctly sending the css files, but there seems to be issues with respect to some admin js files. It is unable to read files in the admin/js/vendor/* . Any help or advise would be greatly appreciated.
#settings.py
import os
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/1.6/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Blog',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'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 = 'Blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'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',
],
},
},
]
ROOT_URLCONF = 'django_project.urls'
WSGI_APPLICATION = 'django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'eJf9IHxaMe',
'HOST': 'localhost',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/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/1.6/howto/static-files/
STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(BASE_DIR,"static")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
#'/var/www/static/',
]
STATIC_ROOT = '/home/django/django_project/django_project/static'
MEDIA_URL = '/media/'
MEDIA_ROOT = '/home/django/django_project/django_project/media'
nginx
upstream app_server {
server 127.0.0.1:9000 fail_timeout=0;
}
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /usr/share/nginx/html;
index index.html index.htm;
client_max_body_size 4G;
server_name _;
keepalive_timeout 5;
# Your Django project's media files - amend as required
location /media {
alias /home/django/django_project/django_project/media;
}
# your Django project's static files - amend as required
location /static {
alias /home/django/django_project/django_project/static;
}
# Proxy the static assests for the Django Admin panel
location /static/admin {
alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app_server;
}
}
Console Error
Failed to load resource: the server responded with a status of 404 (Not Found)
http://myipaddress/static/admin/js/vendor/xregexp/xregexp.min.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://myipaddress/static/admin/js/vendor/jquery/jquery.js Failed to load resource: the server responded with a status of 404 (Not Found)
jquery.init.js:7 Uncaught ReferenceError: jQuery is not defined(anonymous function) # jquery.init.js:7
actions.js:2 Uncaught TypeError: Cannot read property 'fn' of undefined(anonymous function) # actions.js:2(anonymous function) # actions.js:139
prepopulate.js:2 Uncaught TypeError: Cannot read property 'fn' of undefined(anonymous function) # prepopulate.js:2(anonymous function) # prepopulate.js:34
http://myipaddress/static/admin/js/vendor/xregexp/xregexp.min.js Failed to load resource: the server responded with a status of 404 (Not Found)
myipaddress Uncaught TypeError: $ is not a function(anonymous function) # myipaddress/:220(anonymous function) # myipaddress/:234
myipaddress/:259 Uncaught TypeError: $ is not a function