I developed a Django application that I deployed in tests on alwaysdata
The application is easily accessible but internationalization does not apply
However, I did 'execute' the internationalization during the deployment in my virtual environnement (/home/mereva/intensetbm-etool) (django-admin makemessages -l fr and django-admin compilesmessages) and I don't have an error message (normal command return)
Locally, I have no problem, my site is well translated into French when the web browser is in French ...
Deployment on alwaysdata is not trivial ...
architecture of my project:
/home/mereva/envTbm (virtual environment)
/home/mereva/intensetbm-etool (project folder containing manage.py)
/home/mereva/intensetbm_static (static file)
/home/mereva/intensetbm-etool/intenseTBM_eTool/settings.py (root of the project containing settings.py)
/home/mereva/intensetbm-etool/locale (Django translation file)
settings.py
import os
import psycopg2.extensions
# 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 = 'rqps9azjw7i0#_(qxirwr!#0w3f)$prsky9l7bt8t-(y)_tiuj'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# ALLOWED_HOSTS = ['127.0.0.1','localhost', '[::1]']
ALLOWED_HOSTS = ['mereva.alwaysdata.net']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'widget_tweaks',
'bootstrap4',
'registration.apps.RegistrationConfig',
'monitor.apps.MonitorConfig',
'randomization.apps.RandomizationConfig',
'parameters.apps.ParametersConfig',
'unblind.apps.UnblindConfig',
'pharmacy.apps.PharmacyConfig',
'export.apps.ExportConfig',
'django_extensions',
# 'debug_toolbar',
'partial_date',
'safedelete',
'simple_history',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'randomization.middleware.stock',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 'debug_toolbar.middleware.DebugToolbarMiddleware',
'simple_history.middleware.HistoryRequestMiddleware',
'django_session_timeout.middleware.SessionTimeoutMiddleware',
# 'randomization.middleware.AutoLogout',
]
ROOT_URLCONF = 'intenseTBM_eTool.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR,'registration/templates'),
os.path.join(BASE_DIR,'monitor/templates'),
os.path.join(BASE_DIR,'randomization/templates'),
os.path.join(BASE_DIR,'unblind/templates'),
os.path.join(BASE_DIR,'pharmacy/templates'),
os.path.join(BASE_DIR,'export/templates'),
os.path.join(BASE_DIR,'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'randomization.context_processors.data_context_processor',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'intenseTBM_eTool.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME':'mereva_intensetbm',
'USER': '******',
'PASSWORD':'*********',
'HOST':'postgresql-mereva.alwaysdata.net',
'PORT':'5432',
'OPTIONS':{
'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE,
'client_encoding': 'UTF8',
},
}
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',
},
{
'NAME': 'registration.validators.MerevaValidator',
},
]
# 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
# Lists of languages site supports.
# LANGUAGES = (
# ('en', _('English')),
# ('fr', _('French')),
# )
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
os.path.join(BASE_DIR,'randomization/static'),
os.path.join(BASE_DIR,'unblind/static'),
os.path.join(BASE_DIR,'pharmacy/static'),
)
STATIC_ROOT = '/home/mereva/intensetbm_static'
# INTERNAL_IPS = ['127.0.0.1']
LOGIN_URL = 'home'
# my_project/settings.py
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
EMAIL_BACKEND = 'randomization.email.CustomEmailBackend'
# paramétrage du seuil de disponibilité des médiaments ASPIRIN/PLACEBO pour la randomisation
# is_randomizable (randomization.models et randomization_extras.py)
DRUG_DISPONIBILITY = 10
# SESSION_EXPIRE_SECONDS = 900 # 900 - >15 minutes = 15 * 60
# SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True
# SESSION_EXPIRE_AFTER_LAST_ACTIVITY_GRACE_PERIOD = 60 # group by minute
# paramètres utilisés pour middleware personalisé AutoLogout en cours d'écriture
TIME = 15*60 # 15 minutes : 15*60 or your time in seconds
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
SESSION_COOKIE_AGE = TIME # change expired session
SESSION_IDLE_TIMEOUT = TIME # logout
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
What exactly do you mean with internationalization doesn't apply?
I see you missed some settings and some middleware, namely LANGUAGES and LANGUAGE_CODE
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware',
...]
from django.utils.translation import gettext_lazy as _
LANGUAGES = [
('fr', _('French')),
('en-US', _('English')),
]
LANGUAGE_CODE = 'en-US'
LOCALE_PATHS = [...]
Next, in the code, you should use ugettext_lazy instead of ugettext and check the locale file and remove all fuzzyies from it, then compile it again.
I can give more suggestions if you'd share a concrete code snippet that doesn't get translated.
Related
This is my settings.py file and I've created a .env file which contains secret key and other stuffs. I tried installing reinstalling python changing path deleting and again adding project and even I reinstalled vs code but it won't work i dont know where's the problem. This command python manage.py runserver or python manage.py shell or any other related commmand won't work
"""Settings.py"""
"""
Django settings for doorstepdelhi project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from decouple import config
import django_heroku
import os
from pathlib import Path
# 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 = config("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config("DEBUG", default=False, cast=bool)
ALLOWED_HOSTS = ["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',
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
"versatileimagefield",
"nested_admin",
'drf_yasg',
"django_extensions",
'channels',
"accounts",
"webtraffic",
"store",
"product",
"shop",
"wishlist",
"payment",
'core',
"room",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"core.middleware.LogMiddleware",
]
ROOT_URLCONF = "doorstepdelhi.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 = "doorstepdelhi.wsgi.application"
ASGI_APPLICATION = 'doorstepdelhi.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
# 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 = "Asia/Kolkata"
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_URL = "/static/"
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, "static")
CORS_ORIGIN_ALLOW_ALL = True
SITE_ID = 1
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DEFAULT_DECIMAL_PLACES = 3
DEFAULT_MAX_DIGITS = 12
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework.authentication.TokenAuthentication",
"rest_framework.authentication.SessionAuthentication",
),
"DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
"DATETIME_FORMAT": "%b %d %Y %H:%M:%S",
}
CSRF_COOKIE_NAME = "csrftoken"
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_EMAIL_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = "username"
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_USERNAME_REQUIRED = True
AUTH_USER_MODEL = "accounts.User"
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
EMAIL_URL = os.environ.get("EMAIL_URL")
SENDGRID_USERNAME = os.environ.get("SENDGRID_USERNAME")
SENDGRID_PASSWORD = os.environ.get("SENDGRID_PASSWORD")
if not EMAIL_URL and SENDGRID_USERNAME and SENDGRID_PASSWORD:
EMAIL_URL = "smtp://%s:%s#smtp.sendgrid.net:587/?tls=True" % (
SENDGRID_USERNAME,
SENDGRID_PASSWORD,
)
REST_AUTH_SERIALIZERS = {
"USER_DETAILS_SERIALIZER": "accounts.serializers.UserSerializer",
}
VERSATILEIMAGEFIELD_RENDITION_KEY_SETS = {
"products": [
("product_gallery", "thumbnail__540x540"),
("product_gallery_2x", "thumbnail__1080x1080"),
("product_small", "thumbnail__60x60"),
("product_small_2x", "thumbnail__120x120"),
("product_list", "thumbnail__255x255"),
("product_list_2x", "thumbnail__510x510"),
],
"background_images": [("header_image", "thumbnail__1080x440")],
"user_avatars": [("default", "thumbnail__445x445")],
}
# VERSATILEIMAGEFIELD_SETTINGS = {
# # Images should be pre-generated on Production environment
# "create_images_on_demand": get_bool_from_env("CREATE_IMAGES_ON_DEMAND", DEBUG)
# }
PLACEHOLDER_IMAGES = {
60: "images/placeholder60x60.png",
120: "images/placeholder120x120.png",
255: "images/placeholder255x255.png",
540: "images/placeholder540x540.png",
1080: "images/placeholder1080x1080.png",
}
# EMAIL
EMAIL_USE_TLS = config("EMAIL_USE_TLS")
EMAIL_USE_SSL = config("EMAIL_USE_SSL")
EMAIL_HOST = config("EMAIL_HOST")
EMAIL_PORT = config("EMAIL_PORT")
EMAIL_HOST_USER = config("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD")
DEFAULT_FROM_EMAIL = config("DEFAULT_FROM_EMAIL")
# CELERY
CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379/0")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER", "redis://redis:6379/0")
# CELERY_TIMEZONE = 'Asia/Kolkata'
# CELERY_TASK_TRACK_STARTED = True
# CELERY_TASK_TIME_LIMIT = 30 * 60
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://redis:6379/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
"KEY_PREFIX": "doorstepdelhi",
}
}
django_heroku.settings(locals())
PAYTM_MERCHANT_ID = config("PAYTM_MERCHANT_ID")
PAYTM_SECRET_KEY = config("PAYTM_SECRET_KEY")
PAYTM_WEBSITE = config("PAYTM_WEBSITE")
PAYTM_CHANNEL_ID = config("PAYTM_CHANNEL_ID")
PAYTM_INDUSTRY_TYPE_ID = config("PAYTM_INDUSTRY_TYPE_ID")
This is the manage.py file
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "doorstepdelhi.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()
This is "where python" output
C:\Users\hp>where python
C:\Users\hp\AppData\Local\Programs\Python\Python39\python.exe
C:\Users\hp\Desktop\New folder\Doorstep-Delhi-Back-end\venv\Scripts\python.exe
I am trying to add a simple bar chart to my app but while going through a tutorial, I've added in the bottom portion to my Settings.py code and now my app will not load at all. I've tried adjusting this line to just 'routing.application' and moving it to the bottom of my code but neither has worked. Any thoughts?
Error:
Traceback (most recent call last):
File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Python38\lib\site-packages\channels\management\commands\runserver.py", line 107, in inner_run
application=self.get_application(options),
File "C:\Python38\lib\site-packages\channels\management\commands\runserver.py", line 132, in get_application
return StaticFilesWrapper(get_default_application())
File "C:\Python38\lib\site-packages\channels\routing.py", line 30, in get_default_application
raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'django_dash.routing
Settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve(strict=True).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 = 'x'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'channels',
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_plotly_dash.apps.DjangoPlotlyDashConfig',
'bootstrap4',
'dpd_static_support',
]
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',
# Adding additional MIDDLEWARE
'whitenoise.middleware.WhiteNoiseMiddleware',
'django_plotly_dash.middleware.BaseMiddleware',
'django_plotly_dash.middleware.ExternalRedirectionMiddleware',
]
ROOT_URLCONF = 'mysite.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 = 'mysite.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/
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_URL = '/static/'
X_FRAME_OPTIONS = 'SAMEORIGIN'
#
# Define folder location of 'static' folder
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# 'django_dash': django app name
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'django_dash', 'static'),
]
# Static content of Plotly components that should
# be handled by the Django staticfiles infrastructure
PLOTLY_COMPONENTS = [
'dash_core_components',
'dash_html_components',
'dash_bootstrap_components',
'dash_renderer',
'dpd_components',
'dpd_static_support',
]
# Staticfiles finders for locating dash app assets and related files (Dash static files)
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django_plotly_dash.finders.DashAssetFinder',
'django_plotly_dash.finders.DashComponentFinder',
'django_plotly_dash.finders.DashAppDirectoryFinder',
]
# Channels config, to use channel layers
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
'hosts': [('127.0.0.1', 6379),],
},
},
}
# Adding ASGI Application
ASGI_APPLICATION = 'django_dash.routing.application'
# ---------- Add Django Dash end --------------------------------
Dash Visual:
import dash
import dash_core_components as dcc
import dash_html_components as html
from django_plotly_dash import DjangoDash
# Read plotly example dataframe to plot barchart
import plotly.express as px
df = px.data.gapminder().query("country=='India'")
external_stylesheets=['https://codepen.io/amyoshino/pen/jzXypZ.css']
# Important: Define Id for Plotly Dash integration in Django
app = DjangoDash('dash_integration_id')
app.css.append_css({
"external_url": external_stylesheets
})
app.layout = html.Div(
html.Div([
# Adding one extar Div
html.Div([
html.H1(children='Multiple Application'),
html.H3(children='Indian Population over time'),
html.Div(children='Dash: Python framework to build web application'),
], className = 'row'),
html.Div([
html.Div([
dcc.Graph(
id='bar-chart',
figure={
'data': [
{'x': df['year'], 'y': df['pop'], 'type': 'bar', 'name': 'SF'},
],
'layout': {
'title': 'Bar Chart Visualization'
}
}
),
], className = 'six columns'),
# Adding one more app/component
html.Div([
dcc.Graph(
id='line-chart',
figure={
'data': [
{'x': df['year'], 'y': df['pop'], 'type': 'line', 'name': 'SF'},
],
'layout': {
'title': 'Line Chart Visualization'
}
}
)
], className = 'six columns')
], className = 'row')
])
)
if __name__ == '__main__':
app.run_server(8052, debug=False)
when I run python manage.py runserver
and I try to visit my site on my local I get the following error:
File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py", line 432, in stored_name
raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name)
ValueError: Missing staticfiles manifest entry for 'inline.bundle.js'
my settings file in full:
"""
Django settings for suitsandtables project.
Generated by 'django-admin startproject' using Django 1.11.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
from decouple import config, Csv
import datetime
# 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 = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=True, cast=bool)
DEBUG_PROPAGATE_EXCEPTIONS = config('DEBUG_PROPAGATE_EXCEPTIONS', default=True, cast=bool)
BLOCKEMAIL = config('BLOCKEMAIL', default=True, cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
# send grid email code
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=True, cast=bool)
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT')
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')
# Amazon S3 code
AWS_UPLOAD_BUCKET = config('AWS_UPLOAD_BUCKET')
AWS_UPLOAD_USERNAME = config('AWS_UPLOAD_USERNAME')
AWS_UPLOAD_GROUP = config('AWS_UPLOAD_GROUP')
AWS_UPLOAD_ROOT_URI = config('AWS_UPLOAD_ROOT_URI')
# Google maps geocode api url and key
googlemapsgeocodeurl = config('googlemapsgeocodeurl')
googlemapsgeocodekey = config('googlemapsgeocodekey')
googlemapsembedbaseurl = config('googlemapsembedbaseurl')
#example request https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY
emaillinks = {
'devroot': 'localhost:4200/',
'devserverroot': 'http://suitsandtables3.herokuapp.com/',
'productionroot': 'http://www.suitsandtables.com/',
'venueuserverify': 'user/venue/validate/',
'clientuserverify': 'user/client/validate/',
'suitsuserverify': 'user/suits/validate/',
'forgotpassword': 'user/forgot-password/validate/'
}
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'rest_framework',
'storages',
'venues',
'suitsandtablessettingsapp',
'Requestforproposal',
'rest_framework_jwt',
'STuser'
]
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 = 'suitsandtables.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['suitsandtables/templates',
'stemail/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 = 'suitsandtables.wsgi.application'
AUTH_USER_MODEL = 'STuser.STUser'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': config('DBNAME'),
'USER': config('DBUSER'),
'PASSWORD': config('DBPASSWORD'),
'HOST': config('DBHOST'),
'PORT': config('DBPORT'),
}
}
#REST Framework
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':(
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
#JWT settings
JWT_AUTH = {
'JWT_ENCODE_HANDLER':
'rest_framework_jwt.utils.jwt_encode_handler',
'JWT_DECODE_HANDLER':
'rest_framework_jwt.utils.jwt_decode_handler',
'JWT_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_payload_handler',
'JWT_PAYLOAD_GET_USER_ID_HANDLER':
'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
'JWT_SECRET_KEY': SECRET_KEY,
'JWT_GET_USER_SECRET_KEY': None,
'JWT_PUBLIC_KEY': None,
'JWT_PRIVATE_KEY': None,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': False,
'JWT_VERIFY_EXPIRATION': False,
'JWT_LEEWAY': 0,
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=20),
'JWT_AUDIENCE': None,
'JWT_ISSUER': None,
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=30),
'JWT_AUTH_HEADER_PREFIX': 'JWT',
'JWT_AUTH_COOKIE': None,
}
# 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
#angular distro root
ANGULAR_APP_DIR = os.path.join(BASE_DIR, 'frontend/dist/')
#image distro root
ASSETS_DIR = os.path.join(BASE_DIR, 'frontend/dist/assets/')
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
#STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
#STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(ANGULAR_APP_DIR),
os.path.join(ASSETS_DIR),
]
What I don't understand is why is this file failing? This is from an angular 6 project. What is the best way to debug this?
I can see the file in my static file directory after collect static is ran, and it looks from other posts this is a white noise issue.
I used a conventional static file directory rather than white noise as a test and the problem still persisted.
debug = false and STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' == CRASH
debug = false and STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' == 200_ok
Also, be sure and update to whitenoise v4+ and read the docs. It is not backwards-compatible with older versions or settings!
I deployed a Django application with Heroku. It works fine when I run it locally. It has a strange behavior in production. For example, when I push a button, the Prod1 variable is supposed to increment by 1. Now sometimes it does +1, sometimes it jumps back to a previous value.
I also have a similar problem with time.time() but it might be related to the same issue...
That's the Django code in "Prod_settings" used in production:
import dj_database_url
from traineau.settings import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES['default'].update(dj_database_url.config())
MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware']
#STATICFILES_STORAGE='whitenoise.storage.CompressedManifestStaticFilesStorage'
#SECRET_KEY = os.environ['SECRET_KEY']
ALLOWED_HOSTS = ['xxx.herokuapp.com']
As I say, everything works fine in Local so I assume the problem might be in Prod_settings..
As an exemple, these are the
Heroku logs
Prod1 variable increments correctly a couple of times and suddenly returns to 0 for no apparent reason. In this example it's zero but if I would continue it make something like (1,2,3,4,5,0,6,1,2,7,8,9,3,4....)
these are the Heroku Config vars:
DATABASE_URL = postgres://xxxxx
DEBUG_COLLECTSTATIC = 1
DJANGO_SETTINGS_MODULE = traineau.prod_settings
these are the settings used locally
import os
# from django.core.exceptions import ImproperlyConfigured
# def get_env_variable(var_name, default_value=None):
# try:
# return os.environ[var_name]
# except KeyError:
# if default_value is None:
# error_msg = "Set the () environment variable", format(var_name)
# raise ImproperlyConfigured(error_msg)
# else:
# return default_value
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
PROJECT_DIR = os.path.dirname(SETTINGS_DIR).decode('utf-8')
RAW_ROOT = os.path.join(PROJECT_DIR, 'raw')
# 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 = get_env_variable('SECRET_KEY', 'xxx')
SECRET_KEY = 'xxx'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['xxx', 'xxx']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'traineau.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 = 'traineau.wsgi.application'
# 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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
os.path.join(BASE_DIR, 'static')
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
And this is the python function for the +1 button:
def ProdL1(request):
global StkL1, Prod1, CL1, TCL1, reload_page, timer, gTime, diffTime,batch_var
raw_dict = {}
print "1Prod1", Prod1
Prod1 = Prod1 + batch_var
raw_dict['L1Prod'] = int(Prod1)
TCL1 = int(((time.time() -gTime)- diffTime)/(Prod1))
raw_dict['L1TC'] = TCL1
CL1 = TCL1 * MOL1 * C
raw_dict['L1Cost'] = CL1
StkL1 = StkL1 + batch_var
seconds=int((time.time() -gTime)- diffTime)
minutes= round(seconds/60, 2)
print "2Prod1", Prod1
return HttpResponse(json.dumps(raw_dict), content_type="application/json")
when im setting Django to Debug=False, I am getting an error 500 when running via gunicorn or via manage.py. when running via manage I do not get any errors in console.
my settings file has the allowed hosts set to ['*']. As soon as I change Debug=True everything works again.
where would I get the output of the 500 if not from the console when running manage.py?
here is my settings file:
'''
Django settings for itapp project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
'''
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import ldap
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/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 = 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',
'django.contrib.humanize',
'home.apps.HomeConfig',
'oncall.apps.OncallConfig',
'tools.apps.ToolsConfig',
'sites.apps.SitesConfig',
'maintenance.apps.MaintenanceConfig',
'service.apps.ServiceConfig',
'monitoring.apps.MonitoringConfig',
'mgmt.apps.MgmtConfig',
'config.apps.ConfigConfig',
'circuits.apps.CircuitsConfig',
'storages',
'imagekit',
'django_celery_results',
'debug_toolbar',
'simple_history',
'crispy_forms',
)
MIDDLEWARE = [
'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',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'simple_history.middleware.HistoryRequestMiddleware',
]
ROOT_URLCONF = 'itapp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR + '/templates/',
],
'APP_DIRS': True,
'OPTIONS': {
'debug' : DEBUG,
'context_processors': [
'django.template.context_processors.debug',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
'django.template.context_processors.static',
'itapp.context_processors.SiteLinks',
'itapp.context_processors.QuickJumpLinks',
],
},
},
]
CRISPY_TEMPLATE_PACK = 'bootstrap3'
WSGI_APPLICATION = 'itapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
'NAME': 'it_app_db_v2',
'USER': '*****',
'PASSWORD': '*****',
'HOST': '****',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/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',
},
]
INTERNAL_IPS = ('127.0.0.1',)
def show_toolbar(request):
return True
DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK" : show_toolbar,
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_L10N = True
USE_TZ = False
When running a production server, according to the Django docs, you can get errors emailed to you, provided that you set the following in your settings.py (change the values with meaningful ones):
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'my.mail.server'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 25
EMAIL_USE_SSL = False
DEFAULT_FROM_EMAIL = 'mydjango#example.com'
SERVER_EMAIL = 'mydjango#example.com'
ADMINS = (
('Your name Here', 'your.email#example.com'),
)
MANAGERS = (
('Your name Here', 'your.email#example.com'),
)