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

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;
}
}

Related

Unable to retrieve static files into a django project from S3 bucket, but able to upload. Any suggestions?

Following is the settings.py file.
I've tried varying combinations of enabling and disabling STATIC_ROOT, status quo remains disabled.
Have added CORS and Bucket policy as per templates available on AWS.
Alas ! Still no CSS rendered.
Django settings for baatcheet project.
Generated by 'django-admin startproject' using Django 4.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import os
from pathlib import Path
import sec
# 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/4.0/howto/deployment/checklist/
with open(os.path.join(BASE_DIR, 'secret_key.txt')) as f:
SECRET_KEY=f.read().strip()
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['https://test-astratechztestapp.pagekite.me', 'localhost', '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',
'base.apps.BaseConfig',
'rest_framework',
'corsheaders',
]
AUTH_USER_MODEL = 'base.User'
MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
'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',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'baatcheet.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
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 = 'baatcheet.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
MEDIA_URL = '/images/'
STATICFILES_DIRS = [
BASE_DIR / 'static',
'static/'
]
MEDIA_ROOT = BASE_DIR / 'static/images'
# #HTTPS settings
# SESSION_COOKIE_SECURE = True
# CSRF_COOKIE_SECURE = True
# SECURE_SSL_REDIRECT = True
#STATIC_ROOT = BASE_DIR / 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ALLOW_ALL_ORIGINS = True
CSRF_TRUSTED_ORIGINS = ['https://test-astratechztestapp.pagekite.me']
AWS_ACCESS_KEY_ID = sec.AWS_KEY
AWS_SECRET_ACCESS_KEY = sec.AWS_ACC_KEY
AWS_STORAGE_BUCKET_NAME = sec.BUCKET_NAME
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
#STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'

nginx+gunicorn+django error Not Found: /static/.. file

I built a python web framework by using django, and I want to deploy it with nginx and gunicorn. However, I keep getting prompted for error about "Not Found: /static/answer/result.png". If I didn't use nginx adnd gunicorn I wouldn't get this error. I don't know what went wrong, please help me, thank you.
(1) settings.py file:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '...%a..............'
DEBUG = True
ALLOWED_HOSTS = ["127.0.0.1", "192.168.43.90", "192.168.2.229"]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"gunicorn",
'UserProfile',
'ImageRecognition',
"KuaiChao",
"HuaXiao"
]
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 = 'LPAI.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 = 'LPAI.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',
},
{
'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_URL = '/static/'
STATIC_ROOT = "static/"
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "templates"),
)
(2) /etc/nginx/sites-avaiable/default file
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name 192.168.2.229;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass 192.168.2.229:5000;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /static {
autoindex on;
alias /home/guomin/resource/gitee/lapi_lz/static; # django app static file
# root /root/exampledir/static/;
}
}
(3) The command I used to start django: gunicorn LPAI.wsgi:application -w 4 -b 192.168.2.229:5000
(4) I get error: Not Found: /static/answer/EJE005/EJE005_1-1367351883672326145-1367316751137640449-result.png
Note that this image exists and its path is /home/guomin/resource/gitee/lapi_lz/static/answer/EJE005/EJE005_1-1367351883672326145-1367316751137640449-result.png
The above is all the relevant information, please help me.

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 + nginx + gunicorn: how to stop caching

I am running Django 2.0 using gunicorn on nginx server. All my pages are not reflecting the changes immediately. How to stop caching
the below are my files:
nginx.conf
server {
listen 80;
server_name sample.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/testapp/testapp_project/test_artciles;
}
location /media/ {
root /home/testapp/testapp_project/test_artciles;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/testapp/testapp_project/test_artciles.sock;
}
}
Django settings.py
import os
from django.contrib import messages
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'ssdjhasjdkhjaskdhkajsdhkjasdhkjh'
DEBUG = True
ALLOWED_HOSTS = ['xx.xxx.xx.xxx','127.0.0.1']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django_extensions',
# local apps
'articles',
'fcm_django',
'corsheaders',
'rest_framework',
)
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 = 'webarticles.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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 = 'webarticles.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ =True
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',
},
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'frontend'),
)
CORS_ORIGIN_WHITELIST = ('xx.xxx.xx.xxx','127.0.0.1')
I am sure its something to do with the server because when i ran this code in localhost on my own laptop before transferring to server, things are reflecting immediately.
You should restart gunicorn to update working version after you changed code on server:
sudo systemctl restart gunicorn
or you can use --reload mode that will update gunicorn once code changed:
gunicorn --workers=2 test:app --reload
You can read about it on docs https://docs.gunicorn.org/en/stable/settings.html#reload
If you are talking about server caching, then here are the steps worked for me:
My implementation details are
gunicorn 19.9.0,
Django 1.11.16,
nginx version: nginx/1.10.3,
Os (Ubuntu)
Gunicorn is not caching already unless you have installed and enabled https://pypi.org/project/gunicorn_cache/
Disabling django caching,
from django.views.decorators.cache import never_cache
#never_cache
def generating the cached data/results():
Disabling ngnix caching
location todisablecaching {
proxy_no_cache 1;
proxy_cache_bypass 1;
...
}
https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_no_cache,
https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_bypass
I hope it work for you as well.

nginx Django Admin JS static files 404 error

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