i have a website build on Django. everything is working fine on local machine but the static file are not getting load on production. Django project is running fine on Debug=False I did install
whitenoise==6.2.0
the error
django settings
SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["*"]
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://54.234.143.251",
]
CSRF_TRUSTED_ORIGINS = [
"http://54.234.143.251",
]
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# app
"applipsync",
"store",
# packages
"whitenoise.runserver_nostatic",
"rest_framework",
"django_q",
"allauth",
"allauth.account",
"allauth.socialaccount",
"crispy_forms",
]
CRISPY_TEMPLATE_PACK = "bootstrap4"
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", #add whitenoise
"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 = "core.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 = "core.wsgi.application"
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_EMAIL_REQUIRED = True
# Make email verification mandatory to avoid junk email accounts
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
]
LOGIN_REDIRECT_URL = "/"
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# settings.py example
Q_CLUSTER = {
"name": "pdm",
"workers": 1,
"recycle": 500,
"timeout": 60,
"retry": 120,
"compress": True,
"save_limit": 250,
"queue_limit": 500,
"cpu_affinity": 1,
"label": "Django Q",
"daemonize_workers": False,
"orm": "default",
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
# settings.py
STATIC_URL = "static/"
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
# PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root
print("BASE_DIR ", BASE_DIR)
print("------------------------------------------")
print(STATIC_ROOT)
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), "templates").replace("\\", "/"),
)
path in aws
Nginx configuration
server {
listen 80;
server_name 54.234.143.251;
client_max_body_size 100M;
sendfile on;
# to avoid any error while fetching fevicon
location = /favicon.ico { access_log off;
log_not_found off;
}
location /static/ {
autoindex on;
alias /home/ubuntu/lipsync-website/app/staticfiles/;
}
location /media/ {
autoindex on;
alias /home/ubuntu/lipsync-website/app/media/;
}
location / {
# communicate via socket file created by Gunicorn
# proxy_pass http://unix:/home/ubuntu/lipsync-website/app/core.sock;
proxy_pass http://0.0.0.0:8000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
}
i did change the path of nginx but still the static files are not getting load on production.
Related
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.
I have a django made app on heroku and I want change the database there from sqlite to postgreSQL.
I have changed the code in setting.py as follows however the data in my local sqlite is still uploaded to heroku.
from socket import gethostname
hostname = gethostname()
if "MY-COMPUTER-NAME" in hostname: #my computer name
# debug
# DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
ALLOWED_HOSTS = ['*']
else:
# online
# DEBUG = False
import dj_database_url
db_from_env = dj_database_url.config()
DATABASES = {
'default': dj_database_url.config()
}
ALLOWED_HOSTS = ['*']
My commands to deploy
git add -A
git commit -m "Change"
git push heroku master
heroku ps:scale web=1
heroku run python manage.py migrate
heroku open
this is a full code of srtting.py
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.abspath(__file__)))
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 = ":)"
# 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 = [
"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 = "personal_portfolio.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["personal_portfolio/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 = "personal_portfolio.wsgi.application"
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
from socket import gethostname
hostname = gethostname()
if "MY-COMPUTER-NAME" in hostname: #my computer name
# debug
# DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
ALLOWED_HOSTS = ['*']
else:
# online
# DEBUG = False
import dj_database_url
db_from_env = dj_database_url.config()
DATABASES = {
'default': dj_database_url.config()
}
ALLOWED_HOSTS = ['*']
# 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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/' # css
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
django_heroku.settings(locals())
try:
from .local_settings import *
except ImportError:
pass
if not DEBUG:
SECRET_KEY = os.environ['SECRET_KEY'] #new
import django_heroku
django_heroku.settings(locals())
I deployed a Django+VueJS application to a Digital Ocean droplet using Nginx, the Django app is working but i can't see the VueJS components loaded by Webpack (i'm using Django-Webpack-Loader).
In my console, i keep seing these errors:
GET http://MYURL/static/vue/js/stopwatch.js net::ERR_ABORTED 404 (Not Found)
GET http://MYURL/static/vue/js/index.js net::ERR_ABORTED 404 (Not Found)
Which means that the static folder was not found. I made sure to use npm run build and manage.py collectstatic and i can see that the static folder is there, even though the app doesn't see it. Here is the path:
django-vue-mpa
|-vue_frontend
|-django_vue_mpa
|-static
The full code of the application is here (i just cloned that repository and tried to deploy it).
Here is my vue.config.js (i think the problem might be here):
const BundleTracker = require("webpack-bundle-tracker");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const pages = {
"stopwatch": {
entry: "./src/stopwatch.js",
chunks: ["chunk-moment", "chunk-vendors"],
},
"index": {
entry: "./src/index.js",
chunks: ["chunk-vendors"],
},
'vue_app_01': {
entry: './src/main.js',
chunks: ['chunk-vendors']
},
'vue_app_02': {
entry: './src/newhampshir.js',
chunks: ['chunk-vendors']
},
}
module.exports = {
pages: pages,
filenameHashing: false,
productionSourceMap: false,
publicPath: process.env.NODE_ENV === 'production'
? '/static/vue'
: 'http://localhost:8080/',
outputDir: '/django-vue-mpa/django_vue_mpa/static/vue/',
chainWebpack: config => {
config.optimization
.splitChunks({
cacheGroups: {
moment: {
test: /[\\/]node_modules[\\/]moment/,
name: "chunk-moment",
chunks: "all",
priority: 5
},
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "chunk-vendors",
chunks: "all",
priority: 1
},
},
});
Object.keys(pages).forEach(page => {
config.plugins.delete(`html-${page}`);
config.plugins.delete(`preload-${page}`);
config.plugins.delete(`prefetch-${page}`);
})
config
.plugin('BundleTracker')
.use(BundleTracker, [{filename: '../vue_frontend/webpack-stats.json'}]);
// Uncomment below to analyze bundle sizes
// config.plugin("BundleAnalyzerPlugin").use(BundleAnalyzerPlugin);
config.resolve.alias
.set('__STATIC__', 'static')
config.devServer
.public('http://localhost:8080')
.host('localhost')
.port(8080)
.hotOnly(true)
.watchOptions({poll: 1000})
.https(false)
.headers({"Access-Control-Allow-Origin": ["*"]})
}
};
Here is my nginx config:
server {
listen 80;
server_name http://MYURL/;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /django-vue-mpa/django_vue_mpa/static;
}
location / {
include proxy_params;
proxy_pass http://unix:/django-vue-mpa/django-vue-mpa.sock;
}
}
And here is my settings.py:
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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'MYKEY'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['MYURL']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webpack_loader',
'django_vue_mpa'
]
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 = 'django_vue_mpa.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 = 'django_vue_mpa.wsgi.application'
VUE_FRONTEND_DIR = os.path.join(BASE_DIR, 'vue_frontend')
WEBPACK_LOADER = {
'DEFAULT': {
'CACHE': not DEBUG,
'BUNDLE_DIR_NAME': 'vue/', # must end with slash
'STATS_FILE': os.path.join(VUE_FRONTEND_DIR, 'webpack-stats.json'),
'POLL_INTERVAL': 0.3,
'TIMEOUT': None,
'IGNORE': [r'.+\.hot-update.js', r'.+\.map']
}
}
# Database
# https://docs.djangoproject.com/en/1.11/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/1.11/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.11/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.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = "/django-vue-mpa/django_vue_mpa/static"
Check the difference between root and alias nginx directives. For your case you should use
location /static/ {
root /django-vue-mpa/django_vue_mpa;
}
instead of
location /static/ {
root /django-vue-mpa/django_vue_mpa/static;
}
You'd see nginx searches files on a wrong path if you looked at its error log.
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;
}
}
I am doing my django project with nginx on google compute engine.
My view file is,
from django.shortcuts import render_to_response
def home(request):
return render_to_response('html/index.html',RequestContext(request))
and my template file index.html
<html>
<head>
<title> Home </title>
</head>
<body>
Wel come to my new project
</body>
</html>
While calling this page alone takes 2.75 seconds to load completely on my server.
It takes 1.8second for FFTB ( waiting time)
Is there any configuration problem for this latency?
my settings file
"""
Django settings for audiotube project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
#Base root is for outside of the project structure
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
rsa_private_key = BASE_DIR + "/lib/rsa/id_rsa"
#Package root is for inside the project
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '46=+9k)k25rb(b9&&wy9y_xtn3rx2stl#%+0-5o-$-un9o&4hn'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
THUMBNAIL_DEBUG = True
ALLOWED_HOSTS = ['localhost','example.com', '*']
# Application definition
INSTALLED_APPS = (
#This is for the site name and inbuild framework
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app0',
'app1',
'ckeditor',
'social.apps.django_app.default',
'sorl.thumbnail',
'compressor',
'template_timings_panel',
)
COMPRESS_ENABLED = True
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# other finders..
'compressor.finders.CompressorFinder',
)
MIDDLEWARE_CLASSES = (
'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 = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',
'USER': 'root',
'PASSWORD': 'password',
'HOST': 'hostingaddre',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = None
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE_ID = 1
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_ROOT = '/home/mysite/staticfiles/'
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = [
os.path.join(PACKAGE_ROOT, "static"),
]
MEDIA_ROOT = os.path.join(PACKAGE_ROOT, "site_media", "media")
MEDIA_URL = '/media/'
# List of callables that know how to import templates from various sources.
TEMPLATE_DIRS = [
os.path.join("templates"),
]
#Template context processors
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
)
# This two setting needed for downloading CKEDITOR
CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'UltraFull',
'height': 300,
'toolbar_UltraFull': [
['Font', 'FontSize', 'Format'],
['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
[
'NumberedList', 'BulletedList', '-',
'Outdent', 'Indent', '-',
'Blockquote', '-',
'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'
],
['Link', 'Unlink', 'Anchor'],
['Image', 'Flash', 'Table', 'HorizontalRule', 'PageBreak', 'Smiley', 'SpecialChar'],
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'],
['TextColor', 'BGColor'],
['Maximize', 'Source'],
],
'toolbarCanCollapse': False,
},
'awesome_ckeditor': {
'toolbar': 'UltraFull',
'height': 300,
'toolbar_UltraFull': [
['Font', 'FontSize', 'Format'],
['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
[
'NumberedList', 'BulletedList', '-',
'Outdent', 'Indent', '-',
'Blockquote', '-',
'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'
],
['Link', 'Unlink', 'Anchor'],
['Image', 'Flash', 'Table', 'HorizontalRule', 'PageBreak', 'Smiley', 'SpecialChar'],
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'],
['TextColor', 'BGColor'],
['Maximize', 'Source'],
],
'toolbarCanCollapse': False,
},
}
AUTHENTICATION_BACKENDS = (
'users.backends.EmailAuthBackend',
'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth2',
'social.backends.twitter.TwitterOAuth',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_FACEBOOK_KEY ="XXXXXXXXXXXXX"
SOCIAL_AUTH_FACEBOOK_SECRET ="XXXXXXXXXXXXX"
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY ="XXXXXXXXXXXXX"
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "XXXXXXXXXXXXX"
SOCIAL_AUTH_FORCE_EMAIL_VALIDATION = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
SITE_URL="http://example.com:8000/"
'''
#Use this for exception handling
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.associate_by_email',
)
'''
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.auth_allowed',
'social.pipeline.social_auth.social_user',
'social.pipeline.user.get_username',
'users.pipeline.require_email',
#'social.pipeline.mail.mail_validation',
'social.pipeline.user.create_user',
'users.pipeline.save_profile',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details',
#'social.pipeline.debug.debug'
)
# login redirect urls
LOGIN_URL = "/signin"
LOGIN_REDIRECT_URL = "/dashboard"
DOMAIN = "http://example.com:8000"
if DEBUG:
INTERNAL_IPS = ('127.0.0.1',)
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
INSTALLED_APPS += (
'debug_toolbar',
)
DEBUG_TOOLBAR_PANELS = (
'template_timings_panel.panels.TemplateTimings.TemplateTimings',
'debug_toolbar.panels.version.VersionDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.sql.SQLPanel',
#'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
#'debug_toolbar.panels.profiling.ProfilingDebugPanel',
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'debug_toolbar.panels.cache.CacheDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
#'debug_toolbar.panels.logger.LoggingPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
PREPEND_WWW = True
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/var/tmp/django_cache',
}
}
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
In example.com which is inside /etc/nginx/site-enabled and site-available
server {
listen 80;
server_name myservername.com;
client_max_body_size 4G;
error_page 502 =200 #maintenance;
location #maintenance {
root /path/to/static/offline/files;
try_files $uri /index.html =503;
}
location /static/ {
alias /home/sim/5vs/staticfiles/;
}
location /media/ {
alias /home/sim/5vs/myproject/myproject/site_media/media/;
expires 30d;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
}
}
in nginx.conf file has
user root;
worker_processes 4;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
gzip_disable "msie6";
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
Could you please tell why it takes long time and what's wrong in my configuration.
On using Profiler
Total time: 1.89419 s
File: /home/staging/live/users/views.py
Function: comingsoon_view at line 93
Line # Hits Time Per Hit % Time Line Contents
93 def comingsoon_view(request):
94 1 2 2.0 0.0 temp = {}
95 1 1894189 1894189.0 100.0 return render(request, 'pages/comingsoon.html',temp)
User using debug server with DEBUG=True setting to run django project. It enables DEBUG toolbar - which is really slow. It's normal time with this settings. If you'll disable this - I think everything will be fine.
If you will still have troubles - I recommend you to check django debug server response time(python manage.py runserver). If it faster then problem is nginx configuration or, if the same - you should check timings with lineprofiler.
If it's production configuration - don't use debug server on production. You should use gunicorn or something similar to run django projects.