I'm starting a new django project on windows for the first time. I have worked on ubuntu and debian before with no problems. But on windows I found it a large task just to get it installed. I finally found a installing tutorial which worked perfectly until I started making a way for static media to be shown. I simply couldn't find a way to make it work, not with the standard django static media handler of apache. So I thought I would make the rest of the page first, or atleast get that to work. But when I made a view.py for my urls it kept saying "No module named views.py" in the browser. I looked through the internet and found a lot of solutions and tried them. I put a __init__ file in the directory where the views is. I then tried to debug the views.py by running it in a python shell and came up with this:
Traceback (most recent call last):
File "C:\wamp\www\mysite\veiws.py", line 5, in <module>
from django.shortcuts import render_to_response
File "C:\Python27\lib\site-packages\django\shortcuts\__init__.py", line 10, in <module>
from django.db.models.manager import Manager
File "C:\Python27\lib\site-packages\django\db\__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "C:\Python27\lib\site-packages\django\utils\functional.py", line 184, in inner
self._setup()
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is
undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable
DJANGO_SETTINGS_MODULE is undefined.`
I finally got the enviromental variable to be mysite.settings but even then it didn't work, because it couldn't find or didn't understand it, and when I tried some other things it came back...
my directory looks like this
C:\wamp\www\
-mysite
-static
-top4.png
-__init__.py
-__init__.pyc
-django.wsgi
-settings.py
-settings.pyc
-urls.py
-urls.pyc
-views.py
-wsgi.py
-wsgi.pyc
-templates
-base.html
-start_page
-manage.py
-testmysql.php
-index.php
views.py:
from django.conf import settings
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
def home(request):
return render_to_response('Start_page.html',RequestContext(request))
urls.py
from django.conf.urls import *
from veiws import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^home/$', home),
)
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT})
settings.py
# Django settings for mysite project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'Ocelot', # Or path to database file if using sqlite3.
'USER': 'root', # 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.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/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 = 'C:/wamp/www/mysite/static'
STATIC_DOC_ROOT = "C:/wamp/www/mysite/static"
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
#os.path.join(PROJECT_DIR,'static'),
"C:/wamp/www/mysite/static"
)
# 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 = '&16j6qmva-7n00_#i6s17$d^_twu80pzv4l2wbt(^67$4s-c70'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'mysite.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"C:/wamp/www/templates"
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
So I can't get a simple page to work, and I have no idea how to get my static files to just be loaded with apache. All help is deeply appreciated.
EDITTED:
I have tried
set DJANGO_SETTINGS_MODULE = 'mysite.settings'
set DJANGO_SETTINGS_MODULE = 'settings'
wsgi.py
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
sys.path.append('C:/wamp/www/mysite')
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
manage.py
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
i have now tried setting the enviromental user variable but it seemed to delete itself
then i ran python.exe manage.py runserver 8000. witch gave me this error:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
443, in execute_from_command_line
utility.execute()
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
69, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "c:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in im
port_module
__import__(name)
File "c:\Python27\lib\site-packages\django\core\management\commands\runserver.
py", line 8, in <module>
from django.core.servers.basehttp import AdminMediaHandler, run, WSGIServerE
xception, get_internal_wsgi_application
File "c:\Python27\lib\site-packages\django\core\servers\basehttp.py", line 26,
in <module>
from django.views import static
File "c:\Python27\lib\site-packages\django\views\static.py", line 95, in <modu
le>
template_translatable = ugettext_noop(u"Index of %(directory)s")
File "c:\Python27\lib\site-packages\django\utils\translation\__init__.py", lin
e 75, in gettext_noop
return _trans.gettext_noop(message)
File "c:\Python27\lib\site-packages\django\utils\translation\__init__.py", lin
e 48, in __getattr__
if settings.USE_I18N:
File "c:\Python27\lib\site-packages\django\utils\functional.py", line 184, in
inner
self._setup()
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 42, in _set
up
self._wrapped = Settings(settings_module)
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 95, in __in
it__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s"
% (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'mysite.settings' (Is it on sys.path?): N
o module named settings
1) Move settings.py to C:\wamp\www\.
2) export DJANGO_SETTINGS_MODULE = 'settings'
If you're on Windows, you can type
set DJANGO_SETTINGS_MODULE = 'settings'
but it will only work until you close the window.
To make it permanent,
a) Start->Settings->Control Panel->System or press Win-Pause
b) Advanced system settings->Environment Variables->New user variable:
c) (name) DJANGO_SETTINGS_MODULE,
(value) settings
then open new terminal window - existing windows are not be affected.
3) Don't debug views.py by running it. It normally doesn't work. Debug through
python manage.py runserver 8000
when you're inside C:\wamp\www\.
Related
I am trying to set up robot framework on django application. I am testing on a skeleton applciation. Following these instructions https://github.com/kitconcept/robotframework-djangolibrary i get error
% robot tests/test.robot
[ ERROR ] Error in file '/Users/user/hci/pipeline/app/tests/test.robot' on line 13: Importing library 'MIDDLEWARE_CLASSES' failed: ModuleNotFoundError: No module named 'MIDDLEWARE_CLASSES'
Traceback (most recent call last):
None
PYTHONPATH:
/Users/user/.pyenv/versions/3.7.2/bin
/Users/user/.pyenv/versions/3.7.2/lib/python37.zip
/Users/user/.pyenv/versions/3.7.2/lib/python3.7
/Users/user/.pyenv/versions/3.7.2/lib/python3.7/lib-dynload
/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages
==============================================================================
Test :: Django Robot Tests
==============================================================================
Scenario: As a visitor I can visit the django default page | FAIL |
Parent suite setup failed:
No keyword with name 'Start Django' found.
------------------------------------------------------------------------------
Test :: Django Robot Tests | FAIL |
Suite setup failed:
No keyword with name 'Start Django' found.
Also suite teardown failed:
No keyword with name 'Stop Django' found.
1 test, 0 passed, 1 failed
==============================================================================
Output: /Users/user/hci/pipeline/app/output.xml
Log: /Users/user/hci/pipeline/app/log.html
Report: /Users/user/hci/pipeline/app/report.html
This is the content of my files
In settings.py I have
"""
Django settings for pipeline project.
Generated by 'django-admin startproject' using Django 3.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-pn)5iu$yix_%r9&t$=ww=3t8ttaxt=qymg#u^4-q#((u_v#'
# 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',
'demo',
'django_jenkins',
]
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',
'DjangoLibrary.middleware.AutologinAuthenticationMiddleware',
'DjangoLibrary.middleware.FactoryBoyMiddleware',
'DjangoLibrary.middleware.QuerySetMiddleware',
]
MIDDLEWARE_CLASSES = (
'django.contrib.auth.middleware.AuthenticationMiddleware',
'DjangoLibrary.middleware.AutologinAuthenticationMiddleware',
'DjangoLibrary.middleware.FactoryBoyMiddleware',
'DjangoLibrary.middleware.QuerySetMiddleware',
)
ROOT_URLCONF = 'pipeline.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 = 'pipeline.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
In test.robot i have
*** Variables ***
${HOSTNAME} 127.0.0.1
${PORT} 55001
${SERVER} http://${HOSTNAME}:${PORT}/
${BROWSER} firefox
*** Settings ***
Documentation Django Robot Tests
Library Selenium2Library timeout=10 implicit_wait=0
Library MIDDLEWARE_CLASSES ${HOSTNAME} ${PORT} path=pipeline/pipeline manage=pipeline/manage.py settings=pipeline.settings
Suite Setup Start Django and open Browser
Suite Teardown Stop Django and close Browser
*** Keywords ***
Start Django and open Browser
Start Django
Open Browser ${SERVER} ${BROWSER}
Stop Django and close browser
Close Browser
Stop Django
*** Test Cases ***
Scenario: As a visitor I can visit the django default page
Go To ${SERVER}
Wait until page contains element id=explanation
Page Should Contain It worked!
Page Should Contain Congratulations on your first Django-powered page.
I am using python3.7.2
UPDATE
I have updated it but now i get this error
% robot tests/test.robot
==============================================================================
Test :: Django Robot Tests
==============================================================================
Traceback (most recent call last):
File "/Users/user/hci/pipeline/app/manage.py", line 22, in <module>
main()
File "/Users/user/hci/pipeline/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
No changes detected
Traceback (most recent call last):
File "/Users/user/hci/pipeline/app/manage.py", line 22, in <module>
main()
File "/Users/user/hci/pipeline/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
Traceback (most recent call last):
File "/Users/user/hci/pipeline/app/manage.py", line 22, in <module>
main()
File "/Users/user/hci/pipeline/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
------------------------------------------------------------------------------
Django started (PID: 51422)
------------------------------------------------------------------------------
Scenario: As a visitor I can visit the django default page | FAIL |
Parent suite setup failed:
WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
------------------------------------------------------------------------------
Django stopped (PID: 51422)
------------------------------------------------------------------------------
Test :: Django Robot Tests | FAIL |
Suite setup failed:
WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
1 test, 0 passed, 1 failed
==============================================================================
Output: /Users/user/hci/pipeline/app/output.xml
Log: /Users/user/hci/pipeline/app/log.html
Report: /Users/user/hci/pipeline/app/report.html
I am using django-organisations to have multiple user-accounts in multiple organisations. However, it is single-schema architecture. In order to make it separate-schema architecture, I am using django-tenants. This is my project structure:-
app->
-------vendors/
-------accounts/
-------conf/
-------templates/
-------manage.py
I have following code:-
models.py
from django.contrib.auth.models import Permission
from django.db import models
from django_tenants.models import TenantMixin, DomainMixin
from organizations.abstract import (
AbstractOrganization,
AbstractOrganizationOwner,
AbstractOrganizationUser,
)
class Vendor(AbstractOrganization, TenantMixin):
street_address = models.CharField(max_length=100, default="")
city = models.CharField(max_length=100, default="")
account = models.ForeignKey(
"accounts.Account", on_delete=models.CASCADE, related_name="vendors"
)
def __str__(self):
return self.schema_name
class VendorUser(AbstractOrganizationUser):
user_type = models.CharField(max_length=1, default="")
permissions = models.ManyToManyField(Permission, blank=True)
class VendorOwner(AbstractOrganizationOwner, DomainMixin):
pass
settings.py
import os
# Django settings for conf project.
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
"default": {
'ENGINE': 'django_tenants.postgresql_backend',
'NAME': '**',
'USER': '**',
'PASSWORD': '**',
'HOST': '**',
'PORT': '**'
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = "America/New_York"
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "en-us"
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/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/"
# 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 = "7#m$nx#q%-$la^fy_(-rhxtvoxk118hrprg=q86f(#k*6^^vf8"
MIDDLEWARE = [
'django_tenants.middleware.main.TenantMainMiddleware',
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = "conf.urls"
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = "conf.wsgi.application"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(PROJECT_ROOT, "templates/")],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.contrib.messages.context_processors.messages",
],
"debug": DEBUG,
},
}
]
SHARED_APPS = [
'django_tenants',
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.admin",
"organizations",
"accounts",
]
TENANT_APPS = [
"django.contrib.contenttypes",
'vendors',
]
INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS]
# MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
# INSTALLED_APPS += ('debug_toolbar',)
INTERNAL_IPS = ("127.0.0.1",)
DEBUG_TOOLBAR_CONFIG = {"INTERCEPT_REDIRECTS": False, "TAG": "body"}
DEBUG_TOOLBAR_PANELS = (
"debug_toolbar.panels.version.VersionDebugPanel",
"debug_toolbar.panels.timer.TimerDebugPanel",
"debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel",
"debug_toolbar.panels.headers.HeaderDebugPanel",
"debug_toolbar.panels.request_vars.RequestVarsDebugPanel",
"debug_toolbar.panels.template.TemplateDebugPanel",
"debug_toolbar.panels.sql.SQLDebugPanel",
"debug_toolbar.panels.signals.SignalDebugPanel",
"debug_toolbar.panels.logger.LoggingPanel",
)
# 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,
}
},
}
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DATABASE_ROUTERS = (
'django_tenants.routers.TenantSyncRouter',
)
TENANT_MODEL = "vendors.Vendor"
TENANT_DOMAIN_MODEL = "vendors.VendorOwner"
admin.py
from django.contrib import admin
from .models import Vendor, VendorUser, VendorOwner
admin.site.register(Vendor)
admin.site.register(VendorUser)
admin.site.register(VendorOwner)
When I try to run (after running ./manage.py migrate_schemas --shared, which works fine) ./manage.py migrate_schemas --tenant, I get following error:-
Traceback (most recent call last):
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "vendors_vendor" does not exist
LINE 1: SELECT "vendors_vendor"."schema_name" FROM "vendors_vendor" ...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/vineet/projects/env-cosgrid/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/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django_tenants/management/commands/migrate_schemas.py", line 63, in handle
executor.run_migrations(tenants=tenants)
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django_tenants/migration_executors/standard.py", line 8, in run_migrations
tenants = tenants or []
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/models/query.py", line 280, in __bool__
self._fetch_all()
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/models/query.py", line 1261, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/models/query.py", line 184, in __iter__
for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size):
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1103, in results_iter
results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1151, in execute_sql
cursor.execute(sql, params)
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "vendors_vendor" does not exist
LINE 1: SELECT "vendors_vendor"."schema_name" FROM "vendors_vendor" ...
I searched about it (1, 2) but they didn't seem to work.
Would appreciate any hint.
I've searched SO and Google and can't find an answer to my problem.
I've launched my virtualenv and ran this command in the terminal:
python bin/process_messages.py
and this error occurs:
Stacktrace:
Traceback (most recent call last):
File "bin/process_messages.py", line 6, in <module>
from xyz.models import get_sku
File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/xyz/models.py", line 19, in <module>
class Suppliers(models.Model):
File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/django/db/models/base.py", line 110, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/django/apps/registry.py", line 247, in get_containing_app_config
self.check_apps_ready()
File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/django/apps/registry.py", line 125, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I thought it wasn't running django.setup so I added that to the script. Here is my code:
#!/usr/bin/env python
import os
import django
import boto3
from xyz.settings import SQS_QUEUE_NAME
from xyz.models import get_sku
__author__ = 'me'
def check_django_environment(default_settings):
# Environment setup for Django project files:
os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if not os.environ.get('DJANGO_SETTINGS_MODULE'):
# Don't override settings if it is specified.
os.environ['DJANGO_SETTINGS_MODULE'] = default_settings
from django.conf import settings
return getattr(settings, 'DEBUG', None)
check_django_environment('xyz.settings')
django.setup()
# Get the service resource
sqs = boto3.resource('sqs')
# Get the queue
queue = sqs.get_queue_by_name(QueueName=SQS_QUEUE_NAME)
for message in queue.receive_messages():
print(message)
if message.message_attributes is not None:
print(message.message_attributes)
#sku = message.message_attributes
db_sku = get_sku(sku)
print(db_sku)
break
My Installed apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'xyz',
]
By importing get_sku, you are importing your models before django.setup() has run. You need to move this import down so it happens after django.setup().
In a stand-alone script that uses Django, I generally have two groups of imports. The first contains the bare minimum to get Django setup, the second contains all the other imports, including models etc.:
#!/usr/bin/env python
import os
import django
__author__ = 'me'
def check_django_environment(default_settings):
# Environment setup for Django project files:
os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if not os.environ.get('DJANGO_SETTINGS_MODULE'):
# Don't override settings if it is specified.
os.environ['DJANGO_SETTINGS_MODULE'] = default_settings
from django.conf import settings
return getattr(settings, 'DEBUG', None)
check_django_environment('xyz.settings')
django.setup()
import boto3
from xyz.settings import SQS_QUEUE_NAME
from xyz.models import get_sku
In addition to knbk's answer, you can also just use manage.py.
Here's an example script, let's say script.py:
from xyz.models import get_sku
if __name__ == '__main__':
print(get_sku)
And you run it like:
./manage.py shell < script.py
Maybe not what you're looking for, but worth knowing, nonetheless.
I've created a virtual environment for a mezzanine project containing the following dependencie
Django==1.7.1
Fabric==1.10.1
Mezzanine==3.1.10
argparse==1.2.1
bleach==1.4.1
django-filebrowser==3.5.7
django-grappelli==2.6.3
future==0.14.3
grappelli-safe==0.3.13
html5lib==0.999
importlib==1.0.3
mezzanine-grappelli==0.1.0
pytz==2014.10
six==1.8.0
unittest2==0.8.0
wsgiref==0.1.2
When I try to run the 'python manage.py createdb' command I get the following error:
Traceback (most recent call last):
File "/home/joe/JoeDevelopsSite/JoeDevelopsSite/manage.py", line 28, in <module>
execute_from_command_line(sys.argv)
File "/home/joe/JoeDevelopsSite/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/joe/JoeDevelopsSite/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/home/joe/JoeDevelopsSite/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/joe/JoeDevelopsSite/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/joe/JoeDevelopsSite/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/joe/JoeDevelopsSite/local/lib/python2.7/site-packages/mezzanine/forms/models.py", line 10, in <module>
from mezzanine.forms import fields
File "/home/joe/JoeDevelopsSite/local/lib/python2.7/site-packages/mezzanine/forms/fields.py", line 9, in <module>
from mezzanine.core.forms import SplitSelectDateTimeWidget
File "/home/joe/JoeDevelopsSite/local/lib/python2.7/site-packages/mezzanine/core/forms.py", line 40, in <module>
if settings.GRAPPELLI_INSTALLED:
File "/home/joe/JoeDevelopsSite/local/lib/python2.7/site-packages/mezzanine/conf/__init__.py", line 184, in __getattr__
return getattr(django_settings, name)
File "/home/joe/JoeDevelopsSite/local/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in __getattr__
return getattr(self._wrapped, name)
AttributeError: 'Settings' object has no attribute 'GRAPPELLI_INSTALLED'
Here's the full settings.py file:
from __future__ import absolute_import, unicode_literals
######################
# MEZZANINE SETTINGS #
######################
# The following settings are already defined with default values in
# the ``defaults.py`` module within each of Mezzanine's apps, but are
# common enough to be put here, commented out, for convenient
# overriding. Please consult the settings documentation for a full list
# of settings Mezzanine implements:
# http://mezzanine.jupo.org/docs/configuration.html#default-settings
# Controls the ordering and grouping of the admin menu.
#
# ADMIN_MENU_ORDER = (
# ("Content", ("pages.Page", "blog.BlogPost",
# "generic.ThreadedComment", ("Media Library", "fb_browse"),)),
# ("Site", ("sites.Site", "redirects.Redirect", "conf.Setting")),
# ("Users", ("auth.User", "auth.Group",)),
# )
# A three item sequence, each containing a sequence of template tags
# used to render the admin dashboard.
#
# DASHBOARD_TAGS = (
# ("blog_tags.quick_blog", "mezzanine_tags.app_list"),
# ("comment_tags.recent_comments",),
# ("mezzanine_tags.recent_actions",),
# )
#
# A sequence of templates used by the ``page_menu`` template tag. Each
# item in the sequence is a three item sequence, containing a unique ID
# for the template, a label for the template, and the template path.
# These templates are then available for selection when editing which
# menus a page should appear in. Note that if a menu template is used
# that doesn't appear in this setting, all pages will appear in it.
# PAGE_MENU_TEMPLATES = (
# (1, "Top navigation bar", "pages/menus/dropdown.html"),
# (2, "Left-hand tree", "pages/menus/tree.html"),
# (3, "Footer", "pages/menus/footer.html"),
# )
# A sequence of fields that will be injected into Mezzanine's (or any
# library's) models. Each item in the sequence is a four item sequence.
# The first two items are the dotted path to the model and its field
# name to be added, and the dotted path to the field class to use for
# the field. The third and fourth items are a sequence of positional
# args and a dictionary of keyword args, to use when creating the
# field instance. When specifying the field class, the path
# ``django.models.db.`` can be omitted for regular Django model fields.
#
# EXTRA_MODEL_FIELDS = (
# (
# # Dotted path to field.
# "mezzanine.blog.models.BlogPost.image",
# # Dotted path to field class.
# "somelib.fields.ImageField",
# # Positional args for field class.
# ("Image",),
# # Keyword args for field class.
# {"blank": True, "upload_to": "blog"},
# ),
# # Example of adding a field to *all* of Mezzanine's content types:
# (
# "mezzanine.pages.models.Page.another_field",
# "IntegerField", # 'django.db.models.' is implied if path is omitted.
# ("Another name",),
# {"blank": True, "default": 1},
# ),
# )
# Setting to turn on featured images for blog posts. Defaults to False.
#
# BLOG_USE_FEATURED_IMAGE = True
# If True, the south application will be automatically added to the
# INSTALLED_APPS setting.
USE_SOUTH = True
######################### MAIN DJANGO SETTINGS #
########################
# People who get code error notifications.
# In the format (('Full Name', 'email#example.com'),
# ('Full Name', 'anotheremail#example.com'))
ADMINS = (
# ('Your Name', 'your_email#domain.com'),
)
MANAGERS = ADMINS
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# 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 = None
# If you set this to True, Django will use timezone-aware datetimes.
USE_TZ = True
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "en"
# Supported languages
_ = lambda s: s
LANGUAGES = (
('en', _('English')),
)
# A boolean that turns on/off debug mode. When set to ``True``, stack traces
# are displayed for error pages. Should always be set to ``False`` in
# production. Best set to ``True`` in local_settings.py
DEBUG = False
# Whether a user's session cookie expires when the Web browser is closed.
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False
# Tuple of IP addresses, as strings, that:
# * See debug comments, when DEBUG is true
# * Receive x-headers
INTERNAL_IPS = ("127.0.0.1",)
# 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",
)
AUTHENTICATION_BACKENDS = ("mezzanine.core.auth_backends.MezzanineBackend",)
# 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',
)
# The numeric mode to set newly-uploaded files to. The value should be
# a mode you'd pass directly to os.chmod.
FILE_UPLOAD_PERMISSIONS = 0o644
#############
# DATABASES#############
DATABASES = {
"default": {
# Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle".
"ENGINE": "django.db.backends.",
# DB name or path to database file if using sqlite3.
"NAME": "",
# Not used with sqlite3.
"USER": "",
# Not used with sqlite3.
"PASSWORD": "",
# Set to empty string for localhost. Not used with sqlite3.
"HOST": "",
# Set to empty string for default. Not used with sqlite3.
"PORT": "",
}
}
#########
# PATHS #
#########
#import os
# Full filesystem path to the project.
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Name of the directory for the project.
PROJECT_DIRNAME = PROJECT_ROOT.split(os.sep)[-1]
# Every cache key will get prefixed with this value - here we set it to
# the name of the directory the project is in to try and use something
# project specific.
CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_DIRNAME
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = "/static/"
# 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 = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/"))
# 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 = STATIC_URL + "media/"
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/"))
# Package/module name to import the root urlpatterns from for the project.
ROOT_URLCONF = "%s.urls" % PROJECT_DIRNAME
# 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_DIRS = (os.path.join(PROJECT_ROOT, "templates"),)
################
# APPLICATIONS #
################
INSTALLED_APPS = (
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.redirects",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.sitemaps",
"django.contrib.staticfiles",
"mezzanine.boot",
"mezzanine.conf",
"mezzanine.core",
"mezzanine.generic",
"mezzanine.blog",
"mezzanine.forms",
"mezzanine.pages",
"mezzanine.galleries",
"mezzanine.twitter",
#"mezzanine.accounts",
#"mezzanine.mobile",
)
# List of processors used by RequestContext to populate the context.
# Each one should be a callable that takes the request object as its
# only parameter and returns a dictionary to add to the context.
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.static",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.core.context_processors.tz",
"mezzanine.conf.context_processors.settings",
"mezzanine.pages.context_processors.page",
)
# List of middleware classes to use. Order is important; in the request phase,
# these middleware classes will be applied in the order given, and in the
# response phase the middleware will be applied in reverse order.
MIDDLEWARE_CLASSES = (
"mezzanine.core.middleware.UpdateCacheMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"mezzanine.core.request.CurrentRequestMiddleware",
"mezzanine.core.middleware.RedirectFallbackMiddleware",
"mezzanine.core.middleware.TemplateForDeviceMiddleware",
"mezzanine.core.middleware.TemplateForHostMiddleware",
"mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware",
"mezzanine.core.middleware.SitePermissionMiddleware",
# Uncomment the following if using any of the SSL settings:
# "mezzanine.core.middleware.SSLRedirectMiddleware",
"mezzanine.pages.middleware.PageMiddleware",
"mezzanine.core.middleware.FetchFromCacheMiddleware",
)
# Store these package names here as they may change in the future since
# at the moment we are using custom forks of them.
PACKAGE_NAME_FILEBROWSER = "filebrowser_safe"
PACKAGE_NAME_GRAPPELLI = "grappelli_safe"
#########################
# OPTIONAL APPLICATIONS #
#########################
# These will be added to ``INSTALLED_APPS``, only if available.
OPTIONAL_APPS = (
"debug_toolbar",
"django_extensions",
"compressor",
PACKAGE_NAME_FILEBROWSER,
PACKAGE_NAME_GRAPPELLI,
)
###################
# DEPLOY SETTINGS #
###################
# These settings are used by the default fabfile.py provided.
# Check fabfile.py for defaults.
#FABRIC = {
# "SSH_USER": "", # SSH username for host deploying to
# "HOSTS": ALLOWED_HOSTS[:1], # List of hosts to deploy to (eg, first host)
# "DOMAINS": ALLOWED_HOSTS, # Domains for public site
# "REPO_URL": "ssh://hg#bitbucket.org/user/project", # Project's repo URL
# "VIRTUALENV_HOME": "", # Absolute remote path for virtualenvs
# "PROJECT_NAME": "", # Unique identifier for project
# "REQUIREMENTS_PATH": "requirements.txt", # Project's pip requirements
# "GUNICORN_PORT": 8000, # Port gunicorn will listen on
# "LOCALE": "en_US.UTF-8", # Should end with ".UTF-8"
# "DB_PASS": "", # Live database password
# "ADMIN_PASS": "", # Live admin user password
# "SECRET_KEY": SECRET_KEY,
# "NEVERCACHE_KEY": NEVERCACHE_KEY,
# }
##################
# LOCAL SETTINGS #
##################
# Allow any settings to be defined in local_settings.py which should be
# ignored in your version control system allowing for settings to be
# defined per machine.
try:
from local_settings import *
except ImportError as e:
if "local_settings" not in str(e):
raise e
####################
# DYNAMIC SETTINGS #
####################
# set_dynamic_settings() will rewrite globals based on what has been
# defined so far, in order to provide some better defaults where
# applicable. We also allow this settings module to be imported
# without Mezzanine installed, as the case may be when using the
# fabfile, where setting the dynamic settings below isn't strictly
# required.
try:
from mezzanine.utils.conf import set_dynamic_settings
except ImportError:
pass
else:
set_dynamic_settings(globals())
I've been unable to find a solution to this error. Would love guidance.
Thanks!
Mezzanine works with Django 1.6. An incorrect version of Django was being used.
I try to execute django (1.4) tutorial admin on windows. But there is not access to css and javascript.
I set in setty.py:
# 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 = 'C:/Python27/Lib/site-packages/django/contrib/admin/'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
My urils:
from django.conf.urls import patterns, include, url
Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
It still doesn't work. Could you please tell how to solve this issue and what's the best way to solve it?
My proect is in c:\django-projects\mysite.
When I execute admin http://127.0.0.1:8000/admin/polls/poll/1/ I can see error of development server:
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", l
ine 68, in __call__
return super(StaticFilesHandler, self).__call__(environ, start_response)
File "C:\Python27\lib\site-packages\django\core\handlers\wsgi.py", line 241, i
n __call__
response = self.get_response(request)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", l
ine 58, in get_response
return self.serve(request)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", l
ine 51, in serve
return serve(request, self.file_path(request.path), insecure=True)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\views.py", line
41, in serve
return static.serve(request, path, document_root=document_root, **kwargs)
File "C:\Python27\lib\site-packages\django\views\static.py", line 57, in serve
mimetype, encoding = mimetypes.guess_type(fullpath)
File "C:\Python27\lib\mimetypes.py", line 294, in guess_type
init()
File "C:\Python27\lib\mimetypes.py", line 355, in init
db.read_windows_registry()
File "C:\Python27\lib\mimetypes.py", line 259, in read_windows_registry
for ctype in enum_types(mimedb):
File "C:\Python27\lib\mimetypes.py", line 249, in enum_types
ctype = ctype.encode(default_encoding) # omit in 3.x!
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal
Here is from settings.py:
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',
'polls'
)
In firebug I get 500 http return code for css and js files and path seems strange to me.
For example:
http://127.0.0.1:8000/static/admin/css/base.css
I tried to added in settings.py:
# 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.
'C:/Python27/Lib/site-packages/django/contrib/admin/static/admin', //here css and js and img folders for for admin
)
And changing urls.py to this one:
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += staticfiles_urlpatterns()
But it still doesn't work.
Django documenation say here: https://docs.djangoproject.com/en/1.4/howto/deployment/wsgi/modwsgi/#serving-the-admin-files that: "The admin files live in (django/contrib/admin/static/admin) of the Django distribution.". But it still doesn't wok.