Django cms migration wrong number (0) of constraints - python

I've been following the Django CMS installation tutorial, but am stuck when configuring Django CMS to work with Django, here:
http://django-cms.readthedocs.org/en/latest/how_to/install.html#configuring-your-project-for-django-cms
When I omit "cms" from the INSTALLED_APPS, the migration succeeds and the default Django page displays in my browser.
However, when I add "cms" to INSTALLED_APS and run "python manage.py migrate", the migration fails as you can see in the code below.
This fails either with an empty database, or running it after the successful migration I mentioned above.
I have altered the order of INSTALLED_APPS but that has no effect.
I've looked at the definition "alter_unique_together" in:
site-packages/django/db/backends/schema.py
but can't make sense of what is failing.
Help appreciated, will provide any extra details required.
Info
Project File Structure
natureschoolssite
manage.py
media/
my.cnf
natureschoolssite/
models.py
settings.py
urls.py
wsgi.py
static/
templates/
base.html
template_1.html
template_2.html
Output of "python manage.py migrate"
Operations to perform:
Synchronize unmigrated apps: treebeard, sekizai, djangocms_admin_style
Apply all migrations: sessions, admin, sites, auth, menus, contenttypes, cms
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sites.0001_initial... OK
Applying cms.0001_initial... OK
Applying cms.0002_auto_20140816_1918... OK
Applying cms.0003_auto_20140926_2347... OK
Applying cms.0004_auto_20140924_1038... OK
Applying cms.0005_auto_20140924_1039... OK
Applying cms.0006_auto_20140924_1110... OK
Applying cms.0007_auto_20141028_1559... OK
Applying cms.0008_auto_20150208_2149... OK
Applying cms.0008_auto_20150121_0059...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/vagrant/.virtualenvs/natureschools/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/vagrant/.virtualenvs/natureschools/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/vagrant/.virtualenvs/natureschools/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/vagrant/.virtualenvs/natureschools/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/home/vagrant/.virtualenvs/natureschools/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 161, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/home/vagrant/.virtualenvs/natureschools/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 68, in migrate
self.apply_migration(migration, fake=fake)
File "/home/vagrant/.virtualenvs/natureschools/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 102, in apply_migration
migration.apply(project_state, schema_editor)
File "/home/vagrant/.virtualenvs/natureschools/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 108, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/home/vagrant/.virtualenvs/natureschools/local/lib/python2.7/site-packages/django/db/migrations/operations/models.py", line 282, in database_forwards
getattr(new_model._meta, self.option_name, set()),
File "/home/vagrant/.virtualenvs/natureschools/local/lib/python2.7/site-packages/django/db/backends/schema.py", line 302, in alter_unique_together
", ".join(columns),
ValueError: Found wrong number (0) of constraints for cms_page(publisher_is_draft, application_namespace)
Output of "pip freeze"
cffi==0.9.2
cmsplugin-filer==0.10.1
cryptography==0.9
Django==1.7.7
django-appconf==1.0.1
django-classy-tags==0.5
django-cms==3.1.0
django-filer==0.9.9
django-mptt==0.6.1
django-polymorphic==0.7.1
django-reversion==1.8.5
django-sekizai==0.7
django-treebeard==3.0
djangocms-admin-style==0.2.2
easy-thumbnails==2.2
enum34==1.0.4
html5lib==0.999
idna==1.1
ipaddress==1.0.7
MySQL-python==1.2.5
mysqlclient==1.3.6
ndg-httpsclient==0.4.0
Pillow==2.8.1
pyasn1==0.1.7
pycparser==2.13
pyOpenSSL==0.15.1
six==1.3.0
South==1.0.2
Unidecode==0.4.17
Settings.py
# -*- coding: utf-8 -*-
"""
Django settings for natureschoolssite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
gettext = lambda s: s
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6x9y_5)$$&$k&so_p5v=if+_4=f!z3%2almz%nha*%*r(vjm#w'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
SITE_ID = 1
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'cms',
'djangocms_admin_style',
'django.contrib.admin',
'django.contrib.messages',
'django.contrib.sites',
'treebeard',
'menus',
'sekizai',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.language.LanguageCookieMiddleware'
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'django.core.context_processors.static',
'sekizai.context_processors.sekizai',
'cms.context_processors.cms_settings',
)
ROOT_URLCONF = 'natureschoolssite.urls'
WSGI_APPLICATION = 'natureschoolssite.wsgi.application'
TEMPLATE_DIRS = (
# The docs say it should be absolute path: BASE_DIR is precisely one.
# Life is wonderful!
os.path.join(BASE_DIR, "templates"),
)
CMS_TEMPLATES = (
('template_1.html', 'Template One'),
('template_2.html', 'Template Two'),
)
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': '/var/www/natureschools/natureschoolssite/my.cnf',
},
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
LANGUAGES = [
('en-us', 'English'),
]
TIME_ZONE = 'GMT'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = "/static/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"

I had a similar problem with the Zinnia blog app. What I ended up doing was that I simply created the indices the migration wants to delete directly in the Postgres shell:
db=> create index on zinnia_entry (slug, creation_date);
CREATE INDEX
db=> create index on zinnia_entry (status, creation_date, start_publication, end_publication);
CREATE INDEX
In your case that might be something like:
db=> create index on cms_page (publisher_is_draft, application_namespace);
Hope it helps!

Related

python manage.py collectstatic - Digital Ocean - Django

I tried again to host my django project on digital ocean and I get this error after I send "python manage.py collectstatic". Can you help me interpret this error? I can't understand if it is correlated to my code in django or something that I wrote wrong during the process of hosting the project on the server.
TRACEBACK
(django_env) mattia#droplet:~/piattaforma$ python manage.py collectstatic
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle
collected = self.collect()
File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect
for path, storage in finder.list(self.ignore_patterns):
File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 130, in list
for path in utils.get_files(storage, ignore_patterns):
File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files
directories, files = storage.listdir(location)
File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/files/storage.py", line 316, in listdir
for entry in os.scandir(path):
FileNotFoundError: [Errno 2] No such file or directory: '/home/mattia/piattaforma/static'
MY DJANGO PROJECT CODE
piattaforma/settings.py
"""
Django settings for piattaforma project.
Generated by 'django-admin startproject' using Django 3.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_j*f+(ceue_ff4hrgfk0l&r+)wrp#b8k2o4*snuenmuo$7yxib'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'accounts',
'core',
'quiz',
'jobs',
'emoji_picker',
'ckeditor',
]
REGISTRATION_DEFAULT_GROUP_NAME="Students"
CKEDITOR_UPLOAD_PATH = "uploads/"
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'piattaforma.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'accounts/templates'),
os.path.join(BASE_DIR, 'core/templates'),
os.path.join(BASE_DIR, 'quiz/templates'),
os.path.join(BASE_DIR, 'jobs/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 = 'piattaforma.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# EMAIL_USE_TLS = True
# EMAIL_HOST = 'smtp.gmail.com'
# EMAIL_PORT = 587
# EMAIL_HOST_USER = 'MIO ACCOUNT'
# EMAIL_HOST_PASSWORD = 'MIA PASSWORD'
# DEFAULT_FROM_EMAIL = 'IL MIO ACCOUNT GMAIL'
# DEFAULT_TO_EMAIL = 'TO EMAIL'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_URL = '/static/'
LOGIN_REDIRECT_URL= '/'
piattaforma/manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'piattaforma.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
You need to setup your STATIC_ROOT variable, that's the absolute path to the directory where collectstatic will collect static files for deployment, according to Django documention.
As you can see here, the STATICFILES_DIRS variable is to set additional directories (instead of only the app ones) that Django will be collect static files and put inside the STATIC_ROOT directory when you run the collectstatic process.
You're getting this error because you're trying to run a collectstatic and it's not finding the directory defines on your STATICFILES_DIRS variable:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
You can create this directory and put some additional static files that you want to collect in there but you also should set you STATIC_ROOT variable which will be the directory your server is going to use to server the static files on your application.

Problem on adding Django app to installed apps and can't migrate

I'm trying to use visual studio for my Django project. My visual studio version is 2017, my Python version is 3.6 and my Django version at the beginning is 1.1.18.
Then I upgrade it to 2.1.5. I make an app then add it to installed apps. But when I migrate the project get this error:
Traceback (most recent call last):
File "E:\Django_Try\Test4\Test4\manage.py", line 17, in <module>
execute_from_command_line(sys.argv)
File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\apps\registry.py", line 89, in populate
app_config = AppConfig.create(entry)
File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\apps\config.py", line 90, in create
module = import_module(entry)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'saeed'
The interactive Python process has exited.
The interactive Python process has exited.
>>>
it seems can' identify my app.
my setting:
"""
Django settings for Test4 project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import posixpath
# 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.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '79c97724-a0e9-44f0-bffd-e255d60e5460'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# Add your apps here to enable them
'saeed',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
#'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Test4.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 = 'Test4.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/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.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
it seems can' identify my app.
Please inform me.
Saeed
Edit: It looks like you've renamed your main/base app (the one that contains settings.py) from Test4 to saeed. You do not need to register the base application in a Django project since it is already the entry-point for the program. It looks like the rest of your settings.py file is configured for the base app being called Test4 rather than saeed (you can tell because of ROOT_URLCONF = 'Test4.urls', for example). You can read more about projects and applications in Django here.
Since it's common practice to have your base app share the same name as your project I'd recommend changing the name of the saeed directory (back) to Test4.
If you want to create a new app you can run:
python manage.py startapp saeed
So your project file structure will look something like this:
Test4/ # project directory
saeed/ # your app
migrations/
models.py
apps.py
Test4/ # base app for the site
settings.py
urls.py
manage.py
requirements.txt
Then put your models in saeed instead of Test4. So your project directory Test4/, will contain Test4/, saeed/, and manage.py, among other things. After you create this new app, the following will work:
Original Answer:
Make sure your saeed/apps.py is configured properly, for example:
# saeed/apps.py
from django.apps import AppConfig
class SaeedConfig(AppConfig):
name = "saeed"
verbose_name = "Saeed"
Then you'll want to change that line in INSTALLED_APPS in settings from just "saeed" to
"saeed.apps.SaeedConfig"
See the docs on configuring applications for more on this.
I think, it is the incorrect file location hierarchy.
Should be so, for example.
project
mysite
settings.py
...
saeed
makemigrations
models.py
apps.py
...
manage.py
Read this

Django collectstatic error: No such file or directory: '/app/appName/static'

I've been getting this collectstatic error when I run the following in command line:
C:\Users\Steven\site1>heroku run python manage.py collectstatic
Running python manage.py collectstatic on my-compository... up, run.9943 (Free)
You have requested to collect static files at the destination
location as specified in your settings:
/app/mynotes/staticfiles
This will overwrite existing files!
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: yes
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle
collected = self.collect()
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect
for path, storage in finder.list(self.ignore_patterns):
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", line 112, in list
for path in utils.get_files(storage, ignore_patterns):
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files
directories, files = storage.listdir(location)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 399, in listdir
for entry in os.listdir(path):
OSError: [Errno 2] No such file or directory: '/app/mynotes/static'
I haven't been able to figure out what was wrong after much searching.
Here's a slight preview of my directory structure:
-site1
- mynotes
- settings.py
- staticfiles (empty)
- wsgi.py
- urls.py
- mynotess
- static
- mynotess
- capture1.jpg
- carousel.css
- capture2.jpg
- templates
- views.py
- other files related to the app
- users
- files related to this app, no static files here
- manage.py
- .gitignore
- requirements.txt
- Procfile
settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
ALLOWED_HOSTS = ['localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'mynotess',
'users',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mynotes.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'mynotes/templates')], #originally empty
'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 = 'mynotes.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.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'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
LOGIN_URL = 'users/login'
BOOTSTRAP3 = {'include_jquery': True}
if os.getcwd() == '/app':
import dj_database_url
DATABASES = {
'default': dj_database_url.config(default='postgres://localhost')
}
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, 'static'))
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
I don't understand why it's giving this error. It doesn't work with just python manage.py collectstatic either, which gives me an error as follows: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. I've specified the path to the static root mynotes/static and it has been set up to collect all the static files there. I don't understand why it's telling me that no such directory exists. Another thing that confuses me too is the line:
/app/mynotes/staticfiles/
I don't have a directory called staticfiles so I'm not sure how this got here. I typed static in my STATIC_ROOT so I'm not sure why it comes out as staticfiles. Is this something to worry about or is this some default thing? Could it be because I changed the code from the last time I deployed it (which was when DEBUG=True) but it hasn't updated? I tried making an empty directory called staticfiles, but it still gives me the same error.
I'm kind of new to Django and any kind of help is greatly appreciated! P.S. I have thoroughly read the docs but I did not get anything useful out of it.
EDIT
I got heroku run python manage.py collectstatic to work. I figured out why staticfiles was there (just had to re-deploy it). But, my JPG/PNG images and CSS are still not appearing in my website after deployment. This is specifically only when DEBUG = False (it works when True). Plus, python manage.py collectstatic still gives the same error, though I'm not sure if it matters?
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.views.static import serve
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^users/', include('users.urls', namespace='users')),
url(r'', include('mynotess.urls', namespace= "mynotess")), #telling it to look into the urls.py in mynotess for more URLS!
]
if not settings.DEBUG:
urlpatterns += [
url(r'^static/(?P<path>.*)$', serve, {
'document_root': settings.STATIC_ROOT,
}),
]

Django ImportError: No module named middleware

I am using Django version 1.8 and python 2.7. I am getting the following error after running my project.
Traceback (most recent call last):
File "C:\Python27\lib\wsgiref\handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", line 63, in __call__
return self.application(environ, start_response)
File "C:\Python27\lib\site-packages\django\core\handlers\wsgi.py", line 170, in __call__
self.load_middleware()
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 50, in load_middleware
mw_class = import_string(middleware_path)
File "C:\Python27\lib\site-packages\django\utils\module_loading.py", line 26, in import_string
module = import_module(module_path)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named middleware
[26/Aug/2015 20:34:29] "GET /favicon.ico HTTP/1.1" 500 59
This is my settings.py file
"""
Django settings for collageapp project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
APP_PATH = os.path.dirname(os.path.abspath(__file__))
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 = '******************************************************'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'manageApp',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'django.contrib.admindocs',
'rest_framework',
)
SITE_ID = 1
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
)
ROOT_URLCONF = 'collageapp.urls'
CORS_ORIGIN_ALLOW_ALL = True
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',
'allauth.account.context_processors.account',
'allauth.socialaccount.context_processors.socialaccount'
],
},
},
]
WSGI_APPLICATION = 'collageapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'college_app',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
# 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/'
I have tried surfing the error but in vain. My same code is working fine in other machine.
Open up a python shell by running python manage.py shell in your project directory.
Run the following commands one at a time in the python shell:
>>> from corsheaders.middleware import CorsMiddleware
>>> from oauth2_provider.middleware import OAuth2TokenMiddleware
>>> from django.contrib.auth.middleware import SessionAuthenticationMiddleware
One of the lines should give you an error like the following:
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named middleware
The line that gives you that error is the missing module that is giving you the problem.
To find the path where the modules are searched, do
>>> import sys; sys.path
Alternatively, if you don't know how to use the python shell, you could just remove the following lines in your settings.MIDDLEWARE_CLASSES one at a time until you don't get that error anymore:
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'corsheaders.middleware.CorsMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
Just reinstall the package that gave you the error.
django.contrib.auth.middleware -> django
corsheaders.middleware -> corsheaders
oauth2_provider.middleware -> oauth2_provider
Make sure that you have all of the supporting packages installed where they can be found. I've run into problems where there are multiple Python interpreters installed, and was inadvertently running Django with one interpreter while installing packages with another. The other thing I would verify is that you have the same versions of the packages on both machines. Pay close attention to corsheaders.middleware.CorsMiddleware and oauth2_provider.middleware.OAuth2TokenMiddleware since they are not part of Django.
For my situation i did the following:
Inspect the settings.py file
Check on the middleware section for any part that could have been deleted ,accidentally and rectify.
For my case the following had been deleted:
django.middleware.security.SecurityMiddleware

using Tinymce for django error.

I am trying to use TinyMCE Editor in django for textarea. I followed the instructions given on django-tinymce.readthedocs.org/en/latest/usage.html#python-code which give me a error
Environment:
Request Method: GET
Request URL: http://localhost:8000/home/
Django Version: 1.6.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tinymce')
Installed Middleware:
('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')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/hussain/django/ali/ali/views.py" in HomePage
6. print " form :: ",form
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/utils/encoding.py" in <lambda>
60. klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/forms.py" in __str__
103. return self.as_table()
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/forms.py" in as_table
223. errors_on_separate_row = False)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/forms.py" in _html_output
186. 'field': six.text_type(bf),
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/forms.py" in __str__
425. return self.as_widget()
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/forms.py" in as_widget
475. return widget.render(name, self.value(), attrs=attrs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/widgets.py" in render
572. options = self.render_options(choices, value)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/widgets.py" in render_options
528. for option_value, option_label in chain(self.choices, choices):
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/models.py" in __iter__
1044. for obj in self.queryset.all():
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/models/query.py" in __iter__
96. self._fetch_all()
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/models/query.py" in _fetch_all
854. self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/models/query.py" in iterator
220. for row in compiler.results_iter():
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/models/sql/compiler.py" in results_iter
710. for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
781. cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/backends/util.py" in execute
69. return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/backends/util.py" in execute
53. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/utils.py" in __exit__
99. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/backends/util.py" in execute
53. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
450. return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /home/
Exception Value: no such table: django_site
I feel to stupid to not get this. :'(.
these are my files.
settings.py
"""
Django settings for ali project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Django settings for corating project.
PROJECT_DIR = os.path.dirname(__file__)
print 'BASE_DIR ',BASE_DIR
print 'PROJECT_DIR ',PROJECT_DIR
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-=153zwy^8$sz%gsw#kb377pp#r3wmcer(4tc$j-h4(^3s+zw+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tinymce',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'ali.urls'
WSGI_APPLICATION = 'ali.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/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.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_DIR, '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 = (
os.path.join(PROJECT_DIR, 'static'),
# 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.
)
TINYMCE_JS_URL = os.path.join(STATIC_URL, "js/tiny_mce/tiny_mce.js")
TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "js/tiny_mce")
print "TINYMCE_JS_ROOT ",TINYMCE_JS_ROOT
print "TINYMCE_JS_URL ",TINYMCE_JS_URL
TEMPLATE_DIRS = (
'/home/hussain/django/ali/ali/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.
)
forms.py
from django import forms
from django.contrib.flatpages.models import FlatPage
from tinymce.widgets import TinyMCE
class FlatPageForm(forms.ModelForm):
content = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
class Meta:
model = FlatPage
views.py
from django.shortcuts import render_to_response
from page.forms import FlatPageForm
def HomePage(request):
form = FlatPageForm()
print " form :: ",form
return render_to_response('HomePage.html',{'form':form})
urls.py
from django.conf.urls import patterns, include, url
from ali.views import HomePage
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'ali.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
#url(r'^admin/', include(admin.site.urls)),
url(r'^home/', 'ali.views.HomePage' ),
url(r'^tinymce/', include('tinymce.urls') ),
)
You don't seem to have installed flatpages app. Also flatpages app depends in sites framework Follow the steps in the documentation to get it right:
--- excerpts --
To install the flatpages app, follow these steps:
Install the sites framework by adding 'django.contrib.sites' to your INSTALLED_APPS setting, if it’s not already in there.
Also make sure you’ve correctly set SITE_ID to the ID of the site the settings file represents. This will usually be 1 (i.e. SITE_ID = 1, but if you’re using the sites framework to manage multiple sites, it could be the ID of a different site.

Categories

Resources