Gunicorn cannot find system Renviron error - python

I have been struggling with this for days, reaching my limit.
I am porting a Django project from using mod_wsgi/httpd to use gunicorn/nginx
I have set up a virtual environment using virtualenv/virtualenvwrapper and pip installed the requirements file into it, as well a gunicorn. The django project is a very complex site with lots of dependencies.
When I start the app using
`python manage.py runserver`
everything runs fine with no errors. However when I try to start with gunicorn
`gunicorn wsgi`
I get this error
```
cannot find system Renviron
Fatal error: unable to open base package
```
I don't even know where to start troubleshooting this. I have added .Renviron files to my user directory, added os.environ["Renviron"]=/path to both the wsgi.py and settings.py files, downgraded RPy2 back to 2.5.6. Nothing seems to help. I don't know what else to do. Any help would be much appreciated.
Here is my set up:
MacOS High Sierra (10.13.5) running in Parallels Desktop Lite 1.3.3 VM
Django==1.9.2
gunicorn=19.9.0
gevent==1.3.4
greenlet==0.4.13
whitenoise==3.3.1
rpy2==2.5.6
Homebrew==1.6.17
R=3.5.1
Django wsgi.py file
"""
WSGI config for ri project.
"""
import os, sys, socket, site
dev_path = "/Users/evans/.virtualenvs/base_env/"
os.environ["R_HOME"]='/usr/local/lib/R/etc/Renviron'
os.environ["Renviron"]='/usr/local/lib/R/etc/Renviron'
host = socket.gethostname()
print "HOST: ",host
site.addsitedir(dev_path+'lib/python2.7/site-packages')
# Activate the virtual environment
# Taken from http://thecodeship.com/deployment/deploy-django-apache-virtualenv-and-mod_wsgi/
activate_env = os.path.expanduser(dev_path+'bin/activate_this.py')
execfile(activate_env, dict(__file__=activate_env))
sys.path.insert(0,'/usr/local/var/django/code')
sys.path.insert(0,'/usr/local/var/django/code/ri')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ri.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Django settings.py file
# Django settings for ri project.
import socket
import sys
import os
os.environ["Renviron"]="/usr/local/lib/R/etc/Renviron"
Renviron="/usr/local/lib/R/etc/Renviron"
R_HOME="/usr/local/lib/R/etc/Renviron"
host = socket.gethostname()
BASE_PATH="/usr/local/var/django/code"
DEBUG = True # will not send email if True, Runserver will not serve static files if False
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ADMINS = (('Mark Evans',),)
MANAGERS = ADMINS
TESTING = 'test' in sys.argv
# explicitly naming this is asked for in django > 1.6
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
DATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2',
# Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'foodb', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'fooadmin',
'PASSWORD': 'foo_admin',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
},
}
if TESTING:
DATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test_db', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'foo',
'PASSWORD': 'foo_admin',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Test runner with no database creation
TEST_RUNNER = 'ri.RiTestRunner.RiTestRunner'
# 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 = ['localhost']
TIME_ZONE = 'America/Los_Angeles'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
USE_L10N = True
USE_TZ = False
ROOT_URLCONF = 'ri.urls'
SETTINGS_FILE_FOLDER = BASE_PATH + '/ri'
#default login redirect path
LOGIN_REDIRECT_URL = '/'
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = BASE_PATH + '/media'
# 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 = '/media/'
# 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 = BASE_PATH + '/static/'
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = ( BASE_PATH + '/static_src/',)
# 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')
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxx'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ BASE_PATH+"/ri/templates",],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
MIDDLEWARE_CLASSES = (
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'debug_panel.middleware.DebugPanelMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
# the following class logs out a user after AUTO_LOGOUT_DELAY amount of time
'ri.middleware.AutoLogout',
)
# Add automatic caching and compression support
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
},
# this cache backend will be used by django-debug-panel
'debug-panel': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/var/tmp/debug-panel-cache',
'OPTIONS': {
'MAX_ENTRIES': 200
}
}
}
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'ri.wsgi.application'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.postgres',
'debug_toolbar',
'debug_panel',
# Put RI apps below this line in alphabetical order
'ri', # in order to access project, target, etc
)

Update - So I was never able to actually find a solution to the problem per se. However I was able to isolate it by commenting out the apps in the INSTALLED_APPS section of settings.py until I found the app that was responsible for the R dependency. Turns out I didn't need it, so I removed that app and now things work.
Still an odd situation though.

The value of R_HOME does not look right. It should be the name of a directory, like "/usr/local/lib/R", not a file.
That said, R may start up just fine by itself, but appears prone to this issue (cannot find system Renviron) when you try to use it from another language, be it Python, Java, or Tcl. It may require the R_HOME environment variable, which it normally doesn't need.

Related

Django ignores test database settings

I have an app deployed on pythonanywhere which runs fine. Problem is that when I want to run test django, my test database settings is completely ignored.
Each time I run test I get the following message.though.
Creating test database for alias 'default'...
Got an error creating the test database: (1044, "Access denied for user 'funnshopp'#'%' to database 'test_funnshopp$funn'")
Database name for the app is funnshopp$funn. It can be seen that django somehow always tries to create the test database by appending test_ to the database name. Never minding what I have in DATABASES settings
Below is my full settings file ( Test runs fine on my PC and I am using Django 2.0, though I started the project with Django 1.11)
"""
Django settings for funnshopp project.
Generated by 'django-admin startproject' using Django 1.11.7.
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 django.urls import reverse_lazy
from django.core.exceptions import ImproperlyConfigured
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def get_env_variable(var_name):
"""Get the environment variable or return exception"""
try:
return os.environ[var_name]
except KeyError:
error_msg = "Set the {} environment variable".format(var_name)
raise ImproperlyConfigured(error_msg)
ENV_ROLE = get_env_variable("ENV_ROLE")
# 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")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
FUNN_PASS = False
if ENV_ROLE == "development":
DEBUG = True
FUNN_PASS = get_env_variable('FUNN_PASS')
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'asset',
'debit',
'communication',
'establishment',
'credit',
'personnel',
'relation',
'debug_toolbar',
'captcha',
'guardian',
'rules',
'coverage',
'django_extensions',
'pure_pagination',
'sorl.thumbnail',
'django_addanother',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
'rules.permissions.ObjectPermissionBackend',
)
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'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 = 'funnshopp.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 = 'funnshopp.wsgi.application'
INTERNAL_IPS = ('127.0.0.1', 'localhost')
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',
]
GOOGLE_RECAPTCHA_SITE_KEY = get_env_variable("GOOGLE_RECAPTCHA_SITE_KEY")
GOOGLE_RECAPTCHA_SECRET_KEY = get_env_variable("GOOGLE_RECAPTCHA_SECRET_KEY")
LOGIN_REDIRECT_URL = reverse_lazy('personnel:dashboard')
LOGIN_URL = reverse_lazy('personnel:login')
LOGOUT_URL = reverse_lazy('personnel:logout')
if ENV_ROLE == "development":
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
else:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '***#gmail.com'
EMAIL_HOST_PASSWORD = '*******'
DEFAULT_FROM_EMAIL = '***#gmail.com'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DEPLOYMENT_PLATFORM = get_env_variable("DEPLOYMENT_PLATFORM")
if DEPLOYMENT_PLATFORM == "heroku-plus-local":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'funn',
'USER': 'postgres',
'PASSWORD': get_env_variable('FUNN_PASS'),
'HOST': 'localhost',
'PORT': 5432
}
}
else: # DEPLOYMENT_PLATFORM == "pythonanywhere"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'USER': 'funnshopp',
'NAME': 'funnshopp$funn',
'PASSWORD': get_env_variable('FUNN_PASS'),
'HOST': 'funnshopp.mysql.pythonanywhere-services.com',
'TEST':{
'ENGINE': 'django.db.backends.sqlite3', # for sqlite3
'NAME':'test.db',
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME':'funnshopp$test_default'
},
},
}
# 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 = 'Africa/Lagos'
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 = 'staticfiles'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
AUTH_USER_MODEL = 'personnel.Person'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
import django_heroku
django_heroku.settings(locals())
Below is the result of pip freeze
alabaster==0.7.10
Babel==2.5.1
beautifulsoup4==4.6.0
certifi==2017.11.5
chardet==3.0.4
colorama==0.3.9
coverage==4.4.2
dj-database-url==0.4.2
dj-static==0.0.6
Django==2.0.1
django-addanother==2.0.0
django-archive==0.1.5
django-braces==1.12.0
django-debug-toolbar==1.9.1
django-extensions==1.9.9
django-guardian==1.4.9
django-heroku==0.2.0
django-pure-pagination==0.3.0
django-recaptcha==1.3.1
django-toolbelt==0.0.1
django-webtest==1.9.2
docutils==0.14
funcsigs==1.0.2
gunicorn==19.7.1
idna==2.6
This is a common and correct behavior. Django when testing will always try to create new database, and you should never try to test you application on your live/production database.
Your tests should be constructed in a way, where you create your objects and then test their behavior. You are using postgres, on heroku and mysql on development server. If you want to use this databases to test you app, you have to add django user to you postgres/mysql with rights to create and delete databases/tables.
You can also avoid this by adding this setting to your settings.py (this is what I like to do when I do not use any other extensions and sqlite3 database is just enough. I run my tests by typing python manage.py test
if any([arg in sys.argv for arg in ['jenkins', 'test']]):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}
I think you should change how you format your settings.py, you must not put if conditions inside it but use different settings based on the environment you are working on!
I recommend you to read this tutorial.
When you have the proper layout you can change the database in the different settings file ;)!
I solved the problem by reorganizing my settings file according to the pattern suggested here Recommended Django Project Layout.
Now my test runs fine on pythonanywhere.
Btw, I created a gist here which deals with the problems of virtual environments and layouts and how to handle virtual environment variables.
As you know, when you are running tests, Django isolates the changes made to the database. That is why it tries to create a database which is denied by the DB engine. You can either:
Create a database, grant access to the user and use --keepdb to run the tests
Or grant access to the DB user to create a database. Something like:
ALTER USER username CREATEDB;

How to integrate djangobb in an existing project?

wget https://bitbucket.org/slav0nic/djangobb_project/get/tip.tar.gz
tar zxvf tip.tar.gz
cd slav0nic-djangobb_project-tip/
pip install -r requirements.txt
cd basic_project/
touch local_settings.py
#set DATABASE
./manage.py syncdb --all
./manage.py collectstatic
./manage.py runserver
This is the installation guidelines mentioned on djangobb support. I'm stuck after installing the requirements.txt. How do I integrate djangobb to my existing project. Django noob here hence the need of help.
Here you can find my guide writen 2 months ago. For now I see that this guide can be few steps less, but it does not change the result :) so I don't see big reason to re-write it. If you have any question once the guide is read, pls ask.
Currently DjangoBB consist from 2 Git pieces:
3 branches for App itself (stable, default and bootstrap3)
2 branches for Project (default and dimka665/*********)
In this tutorial we are going to use bolded versions of DjangoBB.
1) stable/default/botstrap3 — means DjangoBB_Forum as App itself.
Stable branch has the latest version of code so lets use it.
Source
Zip archive
2) default — Django's skeleton project structure with all settings (urls.py, settings.py, templates, etc) needed to launch 'DjangoBB_Forum app'. This is JUST the project skeleton (similiar to ./manage.py startproject) and here DjangoBB_Forum as App is NOT included.
Source
Zip archive
Lets download both archives, extract them and for convenience rename 2 folders that we've got (both have original name 'slav0nic-djangobb-****) to DjangoBB_App for 'stable' App's branch and to DjangoBB_Project for 'default' Project's branch. (We age going to combine files\datas of both archives)
Instalation.
For today (19.09.2015) the latest version of Django is 1.8.4. This tutorial also is 100% applicable for 1.8.2 and 1.8.3. I've not tested earlier versions of Django.
Now DjangoBB_Forum requirements look like this:
Django>=1.6,<1.9 (the actual latest stable version is 1.8.4)
django-haystack>=2.1.0,<2.4 (actual version for the time of this
tutorial is 2.4)
Pillow>=2.1.0 (actual version is 2.9.0)
postmarkup (actual version is 1.2.2)
pygments (actual version is 2.0.2)
pytz>=2015.4 (this is actual version)
django-pagination-py3==1.1.1 (this actual version)
django-allauth (actual version is 0.23.0)
django-messages (actual version is 0.5.1)
django-nocaptcha-recaptcha (actual version is 0.0.18)
whoosh (actual version is 2.7.0)
The biggest problem here with integration DjangoBB_Forum to existing project is settings, because they are different from user to user. I show you my structure as example, prepared urls.py and settings.py to let you to integrate new settings to your project easily with all necessary explanations. Before to use settings.py below, you need to change DATABASES section there with your DB settings. Also much more below you will see 2nd screen with labels for folders\files which explain you what to change in settings.py in, because you have for sure another absolute paths and possibly another relative paths.
Also want to mention, that on the screeens you will see instead of 'settings/settings.py' file, 3 other files (default_settings.py, development.py, production.py). In the manual, saying 'settings.py' I mean YOUR 'settings.py' file whatever it calls, instead of files on the screen.
Initial structure of our project which is ready to accept djangobb_forum (app_shows_and_times and app_places are used just to make feeling of the existing project to which we add djangobb_forum):
/src/bugaga/urls.py
"""bugaga URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import *
from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static
from djangobb_forum import settings as forum_settings
from djangobb_forum.sitemap import SitemapForum, SitemapTopic
sitemaps = {
'forum': SitemapForum,
'topic': SitemapTopic,
}
urlpatterns = patterns('',
# Admin
url(r'^admin/', include(admin.site.urls)),
# Sitemap
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
#My_Apps
url(r'^places/', include('app_places.urls')),
url(r'^shows/', include('app_shows_and_times.urls')),
# DjangoBB_Forum
url(r'^forum/account/', include('allauth.urls')),
url(r'^forum/', include('djangobb_forum.urls', namespace='djangobb')),
)
# PM Extension
if (forum_settings.PM_SUPPORT):
urlpatterns += patterns('',
url(r'^forum/pm/', include('django_messages.urls')),
)
if (settings.DEBUG):
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
/src/bugaga/settings/development.py
# -*- coding: utf-8 -*-
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
#print ("base dir path", BASE_DIR)
ADMINS = (
# ('Your Name', 'your_email#domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'name_of_db',
'USER': 'login_to_db',
'PASSWORD': 'pass_to_db',
'HOST': 'localhost',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'ru-RU'
LANGUAGES = (
('ca', 'Catalan'),
('cs', 'Czech'),
('de', 'German'),
('en', 'English'),
('es', 'Spanish'),
('fo', 'Faroese'),
('fr', 'France'),
('it', 'Italian'),
('lt', 'Lithuanian'),
('mn', 'Mongolian'),
('nl', 'Dutch'),
('pl', 'Polish'),
('ru', 'Russian'),
('uk_UA', 'Ukrainian'),
('vi', 'Vietnamese'),
('zh_CN', 'Chinese'),
)
SITE_ID = 1
# 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.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Kiev'
USE_TZ = True
# 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
# STATIC_ROOT is where the static files get placed from STATIC_URL and STATICFILES_DIRS
# when they are collected by "manage.py collectstatic". Static files are used by Apache\nginx
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
#When you’re developing using Django’s development server, you won’t have anything to do with this setting.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = "/home/antonio/projects/bugaga.com/static/"
# URL prefix for static files in your apps
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# STATICFILES_DIRS is a setting you use to declare non app-specific static files
# You can prefixes for templates, as STATICFILES_DIRS = (("downloads", "/opt/webfiles/stats"),)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
#'/var/www/static/',
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder', # is default; responsible for STATICFILES_DIRS
'django.contrib.staticfiles.finders.AppDirectoriesFinder', # is default; responsible for $app_name/static/
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/home/antonio/projects/bugaga.com/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'YOUR_SECRET_KEY GENERATED BY DJANGO'
# Make this unique, and don't share it with anybody.
if not hasattr(globals(), 'SECRET_KEY'):
SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
try:
SECRET_KEY = open(SECRET_FILE).read().strip()
except IOError:
try:
from random import choice
import string
symbols = ''.join((string.lowercase, string.digits, string.punctuation ))
SECRET_KEY = ''.join([choice(symbols) for i in range(50)])
secret = file(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
raise Exception('Please create a %s file with random characters to generate your secret key!' % SECRET_FILE)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
#DjangoBB_Forum part
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.locale.LocaleMiddleware',
'pagination.middleware.PaginationMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'djangobb_forum.middleware.LastLoginMiddleware',
'djangobb_forum.middleware.UsersOnline',
'djangobb_forum.middleware.TimezoneMiddleware',
)
ROOT_URLCONF = 'bugaga.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# Directories where the engine should look for template source files, in search order.
# 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.
'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',
#DjangoBB_Forum part
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django_messages.context_processors.inbox',
#'allauth.account.context_processors.account', #not required since v0.21.0
#'allauth.socialaccount.context_processors.socialaccount', #not required since v0.21.0
'djangobb_forum.context_processors.forum_settings',
],
#DjangoBB_Forum part
#'loaders': [
# 'django.template.loaders.filesystem.Loader', #is the same as DIRS [] not empty
# 'django.template.loaders.app_directories.Loader', #is the same as APP_DIRS = True
# 'django.template.loaders.eggs.Loader',
#]
},
},
]
PREREQ_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MY_APPS = [
'app_places',
'app_shows_and_times',
]
DJANGOBB_APPS = [
'django.contrib.sites', #required by django-allauth
'django.contrib.sitemaps',
'django.contrib.admindocs',
'django.contrib.humanize',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.openid',
#'allauth.socialaccount.providers.facebook', # at first you need to configure Facebook or
# you will get Error: No Facebook app configured: please add a SocialApp using the Django admin
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.twitter',
'allauth.socialaccount.providers.vk',
'pagination',
'haystack',
'django_messages',
'nocaptcha_recaptcha',
'djangobb_forum',
]
INSTALLED_APPS = PREREQ_APPS + MY_APPS + DJANGOBB_APPS
# 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,
},
}
}
try:
import mailer
INSTALLED_APPS += ('mailer',)
EMAIL_BACKEND = "mailer.backend.DbBackend"
except ImportError:
pass
try:
import south
INSTALLED_APPS += ('south',)
SOUTH_TESTS_MIGRATE = False
except ImportError:
pass
FORCE_SCRIPT_NAME = ''
# Haystack settings
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'djangobb_forum/djangobb_index'),
'INCLUDE_SPELLING': True,
},
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
# Account settings
ACCOUNT_ACTIVATION_DAYS = 10
LOGIN_REDIRECT_URL = '/forum/'
LOGIN_URL = '/forum/account/login/'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
# Cache settings
CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True
# Allauth
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_SIGNUP_FORM_CLASS = 'bugaga.forms.SignupForm'
try:
from local_settings import *
except ImportError:
pass
(0) Lets imagine that we have project_name/src folder somewhere in VirtualEnvironment (should be already installed (properly built-in feature of Python since v3.4)), which we are going to use as the project folder.
Copy all the entire content from
djangobb_project/basic_project/media/*
to
/bugaga.com/media/
Copy all the entire content from
djangobb_project/basic_project/templates/*
to
/bugaga.com/src/templates/
Copy
djangobb_project/basic_project/forms.py
to
/bugaga.com/bugaga.com/src/settings/
Copy from
djangobb_app/ the next stuff:
'djangobb_forum' folder
'requirements.txt' file
'requirements_optional.txt' file
to
/bugaga.com/bugaga.com/src/
Now you should have the next structure (new stuff marked by black arrows)
activate your virtenv (see step #0)
cd to '/bugaga.com/bugaga.com/src/' (here is my path to my project)
run 'pip install -r requirements.txt' (pip should be also installed long time ago)
run 'pip install -r requirements_optional.txt'
run 'pip install django-nocaptcha-recaptcha'
run 'pip install whoosh'
in '/bugaga.com/bugaga.com/src/' create a file 'secret.txt' and put there any random string you like, for example 'asd423llkmasdi2'
Now try to './manage.py runsever' and open http://127.0.0.1:8000/forum/. If you get error like:
settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
This means you need to properly set up your DataBase in '/bugaga.com/bugaga.com/src/settings/settings.py'.
From the box (means by default) we have the next settings for DB:
.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
As I use PostgreSQL, I can provide DB template for PostgreSQL:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'name_of_db',
'USER': 'login_to_db',
'PASSWORD': 'pass_to_db',
'HOST': 'localhost',
'PORT': '',
}
}
If you did not see the error above, then you should see the error below:
django.db.utils.ProgrammingError: relation "djangobb_forum_forum" does not exist
LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "djangobb_…
:)
run './manage.py migrate'
If you got error:
django.db.utils.ProgrammingError: relation "auth_user" does not exist
-> run './manage.py migrate auth'
If you got error:
psycopg2.ProgrammingError: relation "django_site" does not exist
LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1
-> run './manage.py migrate sites'
run './manage.py migrate' (it migrates the rest apps all together so you dont need to specify the name each of them).
run './manage.py makemigrations'
Again run './manage.py migrate'
Before you can open in the browser your forum, you need to have an account ('./manage.py createsuperuser') othewise you will get errors:
in browser: User matching query does not exist.
in console: django.contrib.auth.models.DoesNotExist: User matching query does not exist.
Also to avoid error:
ImportError: No module named 'allauth.account.context_processors'
-> open 'bugaga.com/bugaga.com/src/settings/settings.py' and in the TEMPLATE_CONTEXT_PROCESSORS section comment (by #) 2 lines like this:
# 'allauth.account.context_processors.account',
# 'allauth.socialaccount.context_processors.socialaccount',
Now we can open our forum but there is 1 remained issue with languages. To fix it, cd to '/src/djangobb_forum/' and run 'django-admin compilemessages'
Now you can run './manage.py runserver' and welcome to DjangoBB_Forum http://127.0.0.1:8000/forum/

Django Admin Page missing CSS in IIS

I am getting a similar error to this post, but it only happens when I go to the website I set up in IIS 2012R2.
I am following this tutorial to start a web app, and I used this video to set up Django with IIS. I successfully set up the Django using IIS, but I a missing the CSS on the admin page.
Note that the admin page displays the CSS items if I run the page using runserver command.
python manage.py runserver
But if I run it through http://127.0.0.1:8003/admin/ in IE (setup through IIS), I get the picture shown below. I tried this in Chrome, and it gave me same results.
Do I need configure my wfastcgi.py file to show CSS? In the video tutorial, the author talks about a static folder in IIS for JPEGS, Javascript...do I need to configure this?
I am using Django 1.8.4 and Python 3.4.
This is my current configuration:
settings.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&y%=6k2y4z5_ut3z#&1l2lh3v12#zyxws)o&5^fj^ik^79pys('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin', #admin site
'django.contrib.auth', #authentication system
'django.contrib.contenttypes', #framework for content types
'django.contrib.sessions', #ssession framework
'django.contrib.messages', #messaging framework
'django.contrib.staticfiles', #framework for managing static files
'polls',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'FirstSite.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 = 'FirstSite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/
STATIC_URL = '/static/'
urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),]
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "FirstSite.settings")
application = get_wsgi_application()
manage.py
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "FirstSite.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
You should set your STATICFILES_DIRS settings in settings.py, to map to your static folder, where CSS, JS and images are stored.
STATIC_URL = 'http://www.example.com/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Also if you run 'manage.py collectstatic' you should define
STATIC_ROOT = "/path/to/static/destination/folder/"
This is the best way to serve static files.
Reference for STATIC settings: Django Documentation
I was able to find an answer with the help of a colleague.
The answer is highlighted here: Link
If you follow the above solution, please keep in mind the following (which is what the above person mentioned):
The Static folder where you keep all the CSS, jpegs, etc files is not the same as the static folder they are referring to in the solution
Make sure you run the command collectstatic to compile all the static files from the STATIC_URL folder to the STATIC_ROOT folder
When you run the collectstatic it will compile the Admin static files as well

Static content in Django

I am trying to load the static content for my Django which I have upgraded to Django 1.4
The project has been successfuly deployed , but I am unable to find the images and all the static content of the project.
Please find the settings.py file
# Django settings for DataEntry project.
import sys
import os
from path import path
SETTINGS_FILE_FOLDER = path(__file__).parent.abspath()
sys.path.append(SETTINGS_FILE_FOLDER.joinpath("libs").abspath())
DEBUG = True
TEMPLATE_DEBUG = DEBUG
INTERNAL_IPS = ("127.0.0.1", "localhost", "192.168.100.102")
ADMINS = (
(" Hello World ", "hello.world#gmail.com"),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'gototest', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'root', # Not used with sqlite3.
'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
'OPTIONS': {
"init_command": "SET storage_engine=INNODB",
}
}
}
# 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.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Asia/Calcutta'
# 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
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
#MEDIA_ROOT = os.path.join(SETTINGS_FILE_FOLDER,'static')
MEDIA_ROOT = '/static'
STATIC_PATH = '/static'
UPLOAD_DIR = '/Users/iceman/Documents/gototest/qbank/static/uploads'
SITE_NAME = 'demo.com'
SITE_URL = 'http://alphadev.demo.com'
AUTH_PROFILE_MODULE = 'core.UserProfile'
LOGIN_REDIRECT_URL = '/students/login/'
# 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 = ''
#STATIC_ROOT = '/Users/iceman/Documents/gototest/qbank/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 = ' hidden '
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
# 'django.template.loaders.filesystem.load_template_source',
# 'django.template.loaders.app_directories.load_template_source',
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
#'utils.XhtmlMortifierMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
#simplCACHE_BACKEND = 'memcached://127.0.0.1:11211/'
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (
SETTINGS_FILE_FOLDER.joinpath("../templates"),
# 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.
)
TEMPLATE_LOADERS = (
#'django.template.loaders.filesystem.load_template_source',
#'django.template.loaders.app_directories.load_template_source',
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
AUTHENTICATION_BACKENDS = (
'accounts.backends.EmailOrUsernameModelBackend',
'django.contrib.auth.backends.ModelBackend'
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.sites',
'django.contrib.flatpages',
'core',
'tinymce',
'filebrowser',
'tagging',
'tagging_autocomplete',
'django_extensions',
'registration',
'questionmanager',
'corporate',
)
ADMIN_HASH_SECRET = " "
RECAPTCHA_PUBLIC_KEY = " "
RECAPTCHA_PRIVATE_KEY = " "
SERIALIZATION_MODULES = { 'modeljson' : 'wadofstuff.django.serializers.json' }
SOLR_ROOT = "http://dev.demo.com:8080/QuestionSolr"
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.request",
"django.core.context_processors.i18n",
"utils.context_processor",
"qutils.context_processor",
)
#'plugins': "table,paste,searchreplace,safari,asciimath,contextmenu",
TINYMCE_JS_URL = "/static/tinymce/tiny_mce/tiny_mce.js"
TINYMCE_JS_ROOT ="/static/tinymce/tiny_mce"
TINYMCE_DEFAULT_CONFIG = {
'plugins': "table,asciimath,gototest,indicime",
'mode' : "textareas",
'theme': "advanced",
'cleanup_on_startup': True,
'custom_undo_redo_levels': 10,
'theme_advanced_buttons1' : "fontselect,fontsizeselect,formatselect,bold,italic,underline,strikethrough,separator,sub,sup,separator,cut,copy,paste,undo,redo",
'theme_advanced_buttons2' : "justifyleft,justifycenter,justifyright,justifyfull,separator,numlist,bullist,outdent,indent,separator,forecolor",
'theme_advanced_buttons3' : "gototest,backcolor,separator,hr,link,unlink,image,table,code,separator,asciimath,asciimathcharmap,indicime",
'theme_advanced_fonts' : "Arial=arial,helvetica,sans-serif,Courier New=courier new,courier,monospace,Georgia=georgia,times new roman,times,serif,Tahoma=tahoma,arial,helvetica,sans-serif,Times=times new roman,times,serif,Verdana=verdana,arial,helvetica,sans-serif",
'theme_advanced_toolbar_location' : "top",
'theme_advanced_toolbar_align' : "left",
'theme_advanced_statusbar_location' : "bottom",
'tab_focus' : ':prev,:next',
}
#'content_css' : "/static/css/content.css",
TINYMCE_SPELLCHECKER = False
TINYMCE_COMPRESSOR = True
FORCE_LOWERCASE_TAGS = True
MARKITUP_FILTER = ('markdown.markdown', {'safe_mode': True})
MARKITUP_SET = 'markitup/sets/markdown'
MARKITUP_SKIN = 'markitup/skins/markitup'
MARKITUP_MEDIA_URL = '/static/'
MARKITUP_AUTO_PREVIEW = True
JQUERY_URL = '/static/js/jquery-1.3.2.min.js'
TAGGING_AUTOCOMPLETE_JS_BASE_URL = "/static"
try:
from local_settings import *
except ImportError: pass
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
When I am looking for the images on the browser URL = http://127.0.0.1:8000/static/site_img/logo.gif
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/static/site_img/logo.gif
"/Users/iceman/Documents/gototest/qbank/qbank/static/site_img/logo.gif" does not exist
To anwer your specific problem, i thing your STATICFILES_DIRS key is missing.
This appear to be your debug config file, so I suppose you want to serve your files with django built-in developement web server (ie: doing "manage.py runserver 8000")
1. DEBUG=True|False
You must know that django should not be used to serve files in production and will refuse to do so.
If you have "DEBUG=False", django will refuse to serve static files by default.
You have to use another server (most people use nginx, or an online cloud service, like cloudfront for this)
For this there is a 2 step process
1. You need to collect static files
2. Set up another server to serve them
When developping this is not convenient, so django look into STATICFILES_DIRS for you, and serve static files
2. Collecting files
A django website is made of multiple applications (see "INSTALLED_APPS" key in your config).
Each one of them may declare static files, all in different directories in your filesystem.
For your files to be properly served, you need them to be grouped in a single local directory, or a single remote server, hence the "./manage.py collectstatic".
This command will scan every directory listed in STATICFILES_DIRS and every "static" directory in loaded applications, and then copy files to the place you want with STATICFILES_STORAGE and STATIC_ROOT)
3. Config keys
# Tells django where your static files are
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), '../static/generated'),
os.path.join(os.path.dirname(__file__), '../static/fixed'),
)
# Only for developpement
# Tells to django build in web server where to host your files ("http://localhost/static")
STATIC_URL = '/static/'
# for production, tell django how do {% static %} template tags and "./manage collectstatic" behave (collect files to a single directory, upload them to a CDN, etc)
#
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
# Only for production when using default value for STATICFILES_STORAGE
# Tell django where to collect files when you run "./manage.py collectstatic".
# This is only used if you host your static files in the same machine as the rest of your application
STATIC_ROOT = '/var/www/static.mydomain.com/'
Try to add STATICFILES_FINDERS and STATICFILES_STORAGE (for deployment) to your settings file.
This will make your life much easier in Django: you put a static folder in each of your apps for when you develop, and when you deploy, you run the collect_static command on your project and all the statics from all the apps will be gathered in the folder specified in the STATICFILES_STORAGE settings.
In the deployment environment, the STATICFILES_STORAGE should be served by the web server.

Not able to use Django mongodb engine with Django?

I have django installed on my server with pymongo and mongoengine.My django project settings.py file :
# Django settings
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'RTSdatabase', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '27017', # Set to empty string for default. Not used with sqlite3.
'SUPPORTS_TRANSACTIONS': False,
}
}
# 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/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
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
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: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# 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 = 't!0pa3z_(gzlb(sai&f$zs4cz9_2u=u(6&g99swo%psrastav6'
# 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',
)
ROOT_URLCONF = 'RTS.urls'
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',
'RTS.RESTAPI',
)
# 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.
# 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,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
whenever i try to access the project it gives me error:
Exception Value: 'django_mongodb_engine' isn't an available database
backend. Try using django.db.backends.XXX, where XXX is one of:
'dummy', 'mysql', 'oracle', 'postgresql', 'postgresql_psycopg2', 'sqlite3' Error was: No module named django_mongodb_engine.base
I dont know what am I doing wrong here in settings file.I am following http://www.chrisumbel.com/article/django_python_mongodb_engine_mongo for help.
The code in that linked article has django_mongodb_engine.mongodb for the ENGINE setting.
You'll also need django-nonrel for this to work.
make sure your depended packages is installed correctly.
you can follow installation to fix your problem.
you can remove the default django installation by
sudo pip uninstall django
and reinstalled from Django fork(https://github.com/django-nonrel/django) with support for NoSQL databases by
sudo pip install git+https://github.com/django-nonrel/django
and remove/comment MIDDLEWARE_CLASSES from setting.py
# 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
# 'django.middleware.security.SecurityMiddleware',

Categories