How to solve ORA-12505 without SID - django

I'm working on a django project, and when trying to connect to an Oracle database I get this message:
DataBaseError: ORA-12505: TNS:listener does not currently know of SID given in
connect descriptor
All the answers online have said "You need to make sure you have the correct SID", so I asked the person at my work who manages all the databases and he said "We don't have SID's for these guys. We use service names instead."
I can access the db via the command line, but trying to get django to do this is driving me crazy. Any help would be greatly appreciated. Thanks
EDIT: Here is my settings.py file. It's not too interesting... this is a fresh project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = ( ,
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': '',
'USER': 'a_user',
'PASSWORD': 'a_password',
'HOST': 'a_host',
'PORT': '1521',
}
}
TIME_ZONE = 'Europe/London'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'sandbox.urls'
WSGI_APPLICATION = 'sandbox.wsgi.application'
TEMPLATE_DIRS = (
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}

If you have DBA access, you can get the SID with:
select instance from V$THREAD;
Typically, it's the same name used in your TNSNAMES.ORA file (MYDB in the below case).
MYDB =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = dbserver.mynetwork)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = MYDB.mynetwork)
)
)
So the settings would be:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'MYDB',
'USER': 'a_user',
'PASSWORD': 'a_password',
'HOST': 'dbserver.mynetwork',
'PORT': '1521',
}
}

For anyone else that might face a similar issue here is another way that worked for me....if you just have the Service name and not the SID then use the following steps to setup your Django settings:
1. Get the instance name using following SQL
select sys_context('userenv','instance_name') from dual; --=><Myinstance>
Replace that in settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': '<Myinstance>',
'USER': 'a_user',
'PASSWORD': 'a_password',
'HOST': 'dbserver.mynetwork',
'PORT': '1521',
}
}

If you're not a DBA or don't have access to the SID for some reason, but you have access to a tsnames.ora file, then you can set up the 'NAME' key in the database set up by using the value on the left side of the equals operator. For example, if you had this entry in the tsnames.ora file:
DATABASE1 =
(DESCRIPTION = ...
)
... your DATABASES variable in settings.py would be set up with 'DATABASE1' being the value of the 'NAME' key (host and port will be blank, since those are referenced by the DATABASE1 entry in your tsnames.ora file).
This, of course, assumes that you have your environment variables (ORACLE_HOME, particularly) established so that the system can access these when referencing this variable.

Related

Error 404 not found raises 500 when Debug set to False

I recently tried to implement a custom view for my 404 and 500 errors on my website. It works well when debug is set to True, i.e. both the custom views work well when called. But as soon as set my Debug to False only the error 500 will be raised
I tried already to call them by creating a url, both of the handler404 and handler500 custom view works well.
This is the view where it should raise an error 404 when badly called:
def arret(request, id):
""" Page that show an textuel """
view = 'search/arret.html'
arret = get_object_or_404(Arret, id=id)
arret.compute_bgeref_id()
query = request.GET.get('q', '')
form_class = DecisionForm()
title = arret.highlight_words(query,input_text=arret.title)
text = arret.highlight_words(query)
arret_judges = arret.arret_judges.all()
decision = arret.decision
return render(request, view, {'title': title,'text': text, 'date':arret.date, 'tag_string': arret.tag_string, 'tags': arret.get_n_tags(), 'articles': arret.get_n_law_articles(n=15),
'bgeref_id': arret.bgeref_ids.all(),"form": form_class, 'id':id, 'query' : query, 'decision': decision,'arret_judges':arret_judges, 'ATF':arret.source=='ATF'
})
Here you can find my 404 custom view:
def handler404(request, template_name="colorlib-error-404-19/index.html"):
response = render_to_response("colorlib-error-404-19/index.html")
response.status_code = 404
return response
it raises an error 500 when trying to find a non existing Arret.
this is what is written in the terminal
System check identified no issues (0 silenced).
June 22, 2019 - 08:55:31
Django version 2.0, using settings 'nora.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[22/Jun/2019 08:55:32] "GET /arret/100/?q=loi HTTP/1.1" 500 1435
Edit: add settings file
Here is my settings_file:
import os
from django.utils.translation import gettext_lazy as _
from requests_aws4auth import AWS4Auth
import elasticsearch
user = os.getenv('USER')
# 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.10/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
if user == 'user':
DEBUG = False
else:
DEBUG = True
# ALLOWED_HOSTS
if user == 'user': # Checks if the settings is on the website
ALLOWED_HOSTS = [ '.neuralen.ch', '.mstamenk.webfactional.com' ]
else :
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'haystack',
'search',
'authUser',
'debug_toolbar',
'haystack_panel',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'nora.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',
"django.template.context_processors.i18n",
],
},
},
]
#TEMPLATE_DIRS = ( failed attempt
# os.path.join(BASE_DIR, 'templates'),
#)
WSGI_APPLICATION = 'nora.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
if user == 'user': # Check if settings.py is on website server
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'nora_db',
'USER': 'neuralen',
'PASSWORD': #################,
'HOST': '127.0.0.1',
'PORT': '5432',
},
'nora_db_2': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'nora_db_2',
'USER': 'neuralen',
'PASSWORD': '################',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
else: # Otherwise, it's in local
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'nora_db_2': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'second_db.sqlite3'),
},
}
#DATABASE_ROUTERS = ['search.routers.SearchRouter']
# AWS
AACCESS_KEY = ##########################
SECRET_KEY = ##########################
REGION = 'us-east-1'
AWSHOST = 'https://search-nora-y6ko4vsxcd4255tcs4gznzbaou.us-east-1.es.amazonaws.com'
awsauth = AWS4Auth(AACCESS_KEY,SECRET_KEY,REGION,'es')
# Haystack connection to elasticsearch.
#https://stackoverflow.com/questions/35090762/django-haystack-using-amazon-elasticsearch-hosting-with-iam-credentials?rq=1
HAYSTACK_CUSTOM_HIGHLIGHTER ="nora.utils.nora_Highlighter"
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack_es.backends.Elasticsearch5SearchEngine',
#'URL': 'http://127.0.0.1:9200/',
'URL': AWSHOST,
'INDEX_NAME': 'nora',
'INCLUDE_SPELLING' : True,
'KWARGS': {
'port': 443,
'http_auth': awsauth,
'use_ssl': True,
'verify_certs': True,
'connection_class': elasticsearch.RequestsHttpConnection,
}
},
}
if user == 'user':
HAYSTACK_CONNECTIONS['default']['INDEX_NAME'] = 'nora-server'
else:
HAYSTACK_CONNECTIONS['default']['INDEX_NAME'] = 'nora'
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
#LANGUAGE_CODE = 'fr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
gettext = lambda x: x
LANGUAGES = (
('en', _('English')),
('fr', _('French')),
('de', _('German')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
if user == 'user': # Check if on website
STATIC_URL = 'https://neuralen.ch/django_nora_static/'
else: # Otherwise running in local
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static/"),
)
if user == 'user':
STATIC_ROOT = '/home/user/webapps/django_nora_static/'
else:
STATIC_ROOT = os.path.join(BASE_DIR, "static_root/")
# Authentification
LOGIN_URL = 'accounts/login'
LOGIN_REDIRECT_URL = '/'
#SMTP Email Serivce
#https://simpleisbetterthancomplex.com/tutorial/2016/06/13/how-to-send-email.html
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'testsite_app'
EMAIL_HOST_PASSWORD = '################'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'TestSite Team <noreply#example.com>'
#EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # During development only
INTERNAL_IPS = [ '127.0.0.1']
DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
'haystack_panel.panel.HaystackDebugPanel',
]
It could be your settings file does not have ALLOWED_HOSTS
Django 1.5 introduced the allowed hosts setting that is required for security reasons.
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
Add your host here like ['www.example.com'] or ['*'] for a quick test, but don't use ['*'] for production.
Alternatively, it could be you're trying to access some static file without running collectstatic. In most cases, this should be a 404 after loading the response in the view, but if you're accessing them in the code, it could be a 500.

How exactly configure Django to send emails with bug reports?

I am really novice with Django, and I am having troubles in configuring my app to send me emails with the bug reports.
I already set on the settings file the required variables as I saw on the Django documentation, like this:
DEBUG = False
...
ADMINS = [('myname', 'myemail#server')] # For server errors
MANAGERS = [('myname', 'myemail#server')] # For missing pages errors
I provoked a error for testing, but nothing happened, no email. What should I do?
This is the code of the settings file (without sensitive data, of course):
"""
Django settings for genform 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/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '****************************************'
DEBUG = False
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'widget_tweaks',
'generador',
'menu',
'parametros_transformados',
'seguridad',
'tablas_de_no_parametros',
'reportes',
'logger',
'parametros',
'django_openid_auth'
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
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.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
AUTHENTICATION_BACKENDS = (
'django_openid_auth.auth.OpenIDBackend',
'django.contrib.auth.backends.ModelBackend',
)
TEMPLATES = [
{
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS':[os.path.join(os.path.dirname(__file__), '../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',
],
},
},
]
OPENID_UPDATE_DETAILS_FROM_SREG = True
ROOT_URLCONF = 'genform.urls'
WSGI_APPLICATION = 'genform.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '*****',
'USER': '******',
'PASSWORD': '******',
'HOST': '***********',
'PORT': '***',
}
}
STATICFILES_DIRS = (
#os.path.dirname(__file__)+"static",
# Put strings here, like "/home/html/site_media" or "C:/www/django/site_media".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(__file__), '../static'),
)
AUTH_PROFILE_MODULE = 'seguridad.c_perfil_usuario'
LOGIN_REDIRECT_URL = '/index'
OPENID_SSO_SERVER_URL = '***********'
OPENID_CREATE_USERS = True
LANGUAGE_CODE = 'es-es'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
ADMINS = [('MyName', 'myemail#server')]
MANAGERS = [('MyName', 'myemail#server')]
What's your LOGGING configuration?
I use the following in my production environment:
ADMINS = [
('Admin1', 'admin1#mail.com'),
('Admin2', 'admin2#mail.com')
]
MANAGERS = ADMINS
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # for testing
EMAIL_HOST = 'relay.server.com'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(thread)d %(message)s'
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false', ],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins', ],
'level': 'ERROR',
'propagate': True
},
'django.security.DisallowedHost': {
'level': 'ERROR',
'handlers': ['console', 'mail_admins', ],
'propagate': True
}
}
}
Make sure you have a valid EMAIL_BACKEND defined. You can use a service like mailgun or even gmail if you don't have a own SMTP server (EMAIL_HOST).
Thoese settings look correct, but there are other things that may be holding you up.
Email info in settings.py may not be configured
You have overwritten the default log settings in settings.py and are not writing errors to the email log.
If one or both of these are not setup correctly, then you won't get the emails.
To fix 1 you can look at this answer: https://stackoverflow.com/a/4642194/4788717
To fix 2, you can check out the docs: https://docs.djangoproject.com/en/dev/topics/logging/ and make sure you have either the default or mail admins case:
LOGGING = {
...
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['special']
...
}

Css and Javascripts not loading on login page in Django?

Here is my settings file.. I am getting the login page but the css and javascripts are not loading.
I gotthe whole project and i have to start working on it but i only know the basic of django so not sure why css and javascripts arenot loading. this is a very old project so it is using python 2.6.5 and django 1.3. the folder structure is also old.
# Django settings for athena.
import socket
# determine whether it's prod or dev or test/uat
if socket.gethostname().split('.')[0].lower().strip() in ('athena-dev', 'athena-test', 'lucid32'):
ATHENA_PROD_MODE = False
elif socket.gethostname().split('.')[0].lower().strip() == 'athena':
ATHENA_PROD_MODE = True
else:
raise Exception('cannot determine what mode (prod or dev) to operate in')
ATHENA_UAT_MODE = (socket.gethostname().split('.')[0].lower().strip() == 'athena-test')
if ATHENA_PROD_MODE:
DEBUG = False
else:
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (('PASystemSupport', 'pasystemsupport#apa.org'), )
MANAGERS = ADMINS
if ATHENA_PROD_MODE:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'Athena',
'USER': 'ftdbuser',
'PASSWORD': 'f0lt5xt',
'HOST': 'PIDB-SQL',
'OPTIONS': {
'driver': 'SQL Server',
'autocommit': True,
'dsn': 'PIDB-SQL',
'use_mars': True
}
}
}
elif ATHENA_UAT_MODE:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'Athena-UAT',
'USER': 'ftdbuser',
'PASSWORD': 'f0lt5xt',
'HOST': 'LANDB-DEV',
'OPTIONS': {
'driver': 'SQL Server',
'autocommit': True,
'dsn': 'LANDB-DEV',
'use_mars': True
}
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/vagrant/Athena/athena_root/athena.db',
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/New_York'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/vagrant/Athena/athena_root/athena_static/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/athena_static/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '7*f!l)^v!81vog#yzd23scp5+30db=)bub(j88nz!37nnt62mh'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'athena_root.athena.middleware.ApplyAuthentication',
'athena_root.athena.workflow.middleware.ProdViewPermissions'
)
ROOT_URLCONF = 'athena_root.athena.urls'
TEMPLATE_DIRS = ('/vagrant/Athena/athena_root/athena_templates',
'/vagrant/Athena/athena_root/ltt/templates',
'/vagrant/Athena/athena_root/errata/templates')
TEMPLATE_CONTEXT_PROCESSORS = (
"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.request",
"django.contrib.messages.context_processors.messages",
"athena_root.athena.template_context_proc.baseTemplateContext"
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.humanize',
'athena_root.athena',
'athena_root.ltt',
'athena_root.errata'
)
EMAIL_HOST = 'mailhost.apa.org'
SERVER_EMAIL = 'PASystemsupport#apa.org'
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'django.utils.log.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True
},
'aem_db_logger': {
'level': 'DEBUG',
'class': 'athena_root.errata.log.DatabaseLoggingHandler',
'formatter': 'verbose'
}
},
'loggers': {
'django': {
'handlers': ['null'],
'propagate': True,
'level': 'INFO',
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'athena_root.errata': {
'handlers': ['aem_db_logger'],
'level': 'DEBUG',
'propagate': True
}
}
}
AUTHENTICATION_BACKENDS = ('athena_root.athena.auth.backends.AthenaAuthBackend',)
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login'
LOGOUT_URL = '/logout'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_AGE = 7257600
SESSION_SAVE_EVERY_REQUEST = False
`

Dajaxice running locally, but django settings problems to make it work online

I have created a Django account which uses Dajaxice and Dajax.
I run my website in an azure VM. When I run it with localhost Dajaxice/Dajax work perfectly.
However, online this does not work anymore. I have some configurations problems in my settings, but I am unable to fix it.
Locally, Dajaxice/Dajax is pointed in this way:
<script src="/static/dajaxice/dajaxice.core.js" type="text/javascript" charset="utf-8"></script>
The Dajaxice/Dajax function is called like this:
GET http://localhost:1465/dajaxice/chocolate.chocolate.cellphone/?argv=%7B%22cell%22%3A%22jk%22%2C%22pID%22%3A%228353%22%7D
How should I change my settings, so I can access dajaxice online?
This is my settings.py so far:
from os import path
PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))
LOGIN_REDIRECT_URL = ''
HTMLFILES_DIR = 'C:\inetpub\wwwroot\chocolate\chocolate\chocolate\htmlFiles'
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('x', 'x#gmail.com'),
)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
TEMPLATE_CONTEXT_PROCESSORS = (
'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.request',
'django.contrib.messages.context_processors.messages',
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'NAME': 'xx',
'ENGINE': 'x',
'HOST': 'x.x.x',
'USER': 'x#zx',
'PASSWORD': 'x!',
'OPTIONS': {
'provider': 'x'
}
}
}
TIME_ZONE = 'Europe/London'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = HTMLFILES_DIR + '\Pictures'
MEDIA_URL = 'http://localhost:1781/Pictures/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'dajaxice.finders.DajaxiceFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'chocolate.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'chocolate.wsgi.application'
TEMPLATE_DIRS = (
HTMLFILES_DIR
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'chocolate.chocolate',
'dajaxice',
'dajax',
# Uncomment the next line to enable the admin:
'django.contrib.admin'
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
EMAIL_HOST = 'smtp-mail.outlook.com'
EMAIL_HOST_USER = 'x#outlook.com'
EMAIL_HOST_PASSWORD = 'x'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console':{
'level':'INFO',
'class':'logging.StreamHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'dajaxice':{
'handlers': ['console'],
'level': 'INFO',
'propagate': True,
},
}
}
Well, I found how to do it. For anyone with few experience in Django, this information could be helpful.
When I use localhost, having the following information is just fine:
STATIC_ROOT = ''
STATIC_URL = '/static/'
However, once you plan to deploy your application, you need to create a file somewhere in your application and include the path in STATIC_ROOT. In my case, it was the following:
STATIC_ROOT = 'C:/inetpub/wwwroot/chocolate/chocolate/chocolate/static/'
I manually created the file called static, which you can see above. Then, add the name of the file created in STATIC_URL.
STATIC_URL = '/static/'
Afterwards, with your console access the file where you have your app's manage.py . Make sure to have added python as a command and write python manage.py collectstatic . All your static files will located there, in the static file you created. In my case, the files of dajaxice and dajax appeared in this folder after having written python manage.py collectstatic.
Now, dajaxice/dajax should work online after deployment.

ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details

I did exactly what heroku specified on https://devcenter.heroku.com/articles/django
But when I am running heroku run python manage.py syncdb
its saying ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
This is how my settings.py file looks like. I tried all the solutions that I could find nothing seems to help
Django settings for django_synapse project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'h4fm7a&92r1hxa$j&u*7j)61-o2#17k)zy9fncz+7=usn74v%2'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'django_synapse.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'django_synapse.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Both Sultan and Joe are correct, and if you put them together and dig a little it works, I just want to lay it out a little clearer with an addition that helped me. These instructions on the Heroku site explain how to set it up including what Sultan mentioned, adding this section to settings.py:
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Then, (and what those instructions don't mention) in your Heroku account go to your Databases section and select the database you would like to use. Go to 'Connection Settings' (two little arrows going opposite directions) and select the Django option. That code should look like what Joe mentioned:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'your_db_name',
'HOST': 'your_host',
'PORT': '5432',
'USER': 'your_db_user_name',
'PASSWORD': 'your_password',
}
}
Paste this at the bottom of your settings.py file and sync your DB.
Did you try the stuff in the documentation at https://devcenter.heroku.com/articles/django#django-settings?
import dj_database_url
DATABASES['default'] = dj_database_url.config()
It says
Django settings
Next, configure the application for the Heroku environment, including
Heroku’s Postgres database. The dj-database-url module will parse the
values of the DATABASE_URL environment variable and convert them to
something Django can understand.
Make sure ‘dj-database-url’ is in your requirements file, then add the
following to the bottom of your settings.py file:
settings.py
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Your are defining the DATABASES = {'default': {... }} twice.
Solution:
If you are using heroku to serve your database then use this
import dj_database_url
DATABASES['default'] = dj_database_url.config()
if you're trying to connect to an external database server comment the two lines above and use this
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
You haven't defined any of the database info.
Your DATABASES section should look something like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'your_db_name',
'USER': 'your_db_user_name',
'PASSWORD': 'your_password',
'HOST': 'ec2-23-21-133-106.compute-1.amazonaws.com', # Or something like this
'PORT': '5432',
}
}
Why don't you try this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'yourdatabasename',
'HOST': 'localhost',
'PORT': '',
'USER': 'yourusername',
'PASSWORD': 'yourpassword',
}
}
and after that apply this:
db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)