We were forced by the company to move our django app from Linux to Windows. I googled and there I found Helicon Zoo is meant to be a good idea to help me setting this up.
I have installed the zoo part as it was described and tried to add my django application which did not work. To be sure I am not having problems with complex stuff in the application I have created a mysite demopage as it was described in the django tutorial so now I have got this folder structure:
C:\inetpub\wwwroot\ZooPythonProject
I have changed the webconfig so it looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<heliconZoo>
<clear />
<application name="python.project">
<environmentVariables>
<add name="VIRTUAL_ENV" value="%APPL_PHYSICAL_PATH%\venv" />
<add name="PATH" value="%APPL_PHYSICAL_PATH%\venv\Scripts;% PATH%" />
<add name="PYTHONPATH" value="%APPL_PHYSICAL_PATH% \venv\lib\site-packages;%APPL_PHYSICAL_PATH%\venv\lib;%APPL_PHYSICAL_PATH%;% APPL_PHYSICAL_PATH%\mysite" />
<!-- <add name="WSGI_APP" value="welcome.application" /> -->
<add name="CONSOLE_URL" value="console" />
<add name="DEPLOY_FILE" value="deploy.py" />
<add name="ERROR_LOG_DIR" value="log" />
<!-- generic wsgi app -->
<!-- django project --> <add name="DJANGO_SETTINGS_MODULE" value="mysite.settings" />
I know that the setting file is taken as if I change the name of the setting file I get a different error message saying that the file cannot be found.
I start IIS and check my logfile it is giving me this error message:
No handlers could be found for logger "django.request"
Traceback (most recent call last):
File "C:\Zoo\Workers\python\zoofcgi.py", line 1069, in <module>
run_django_app(options.django_settings_module, options.django_root)
File "C:\Zoo\Workers\python\zoofcgi.py", line 999, in run_django_app
FCGIServer(WSGIHandler(), app_root=django_root).run()
File "C:\Zoo\Workers\python\zoofcgi.py", line 776, in run
conn.run()
File "C:\Zoo\Workers\python\zoofcgi.py", line 569, in run
self.process_input()
File "C:\Zoo\Workers\python\zoofcgi.py", line 600, in process_input
self._do_stdin(rec)
File "C:\Zoo\Workers\python\zoofcgi.py", line 724, in _do_stdin
self._start_request(req)
File "C:\Zoo\Workers\python\zoofcgi.py", line 697, in _start_request
req.run()
File "C:\Zoo\Workers\python\zoofcgi.py", line 515, in run
protocolStatus, appStatus = self.server.handler(self)
File "C:\Zoo\Workers\python\zoofcgi.py", line 862, in handler
result = self.application(environ, start_response)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\core\handlers\wsgi.py", line 189, in __call__
response = self.get_response(request)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\core\handlers\base.py", line 218, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\core\handlers\base.py", line 261, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\views\debug.py", line 97, in technical_500_response
html = reporter.get_traceback_html()
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\views\debug.py", line 384, in get_traceback_html
return t.render(c)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\base.py", line 209, in render
return self._render(context)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\base.py", line 201, in _render
return self.nodelist.render(context)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\base.py", line 903, in render
bit = self.render_node(node, context)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\debug.py", line 79, in render_node
return node.render(context)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\debug.py", line 89, in render
output = self.filter_expression.resolve(context)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\base.py", line 674, in resolve
new_obj = func(obj, *arg_vals)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\defaultfilters.py", line 774, in date
return format(value, arg)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\dateformat.py", line 345, in format
return df.format(format_string)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\dateformat.py", line 37, in format
pieces.append(force_text(getattr(self, piece)()))
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\dateformat.py", line 270, in r
return self.format('D, j M Y H:i:s O')
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\dateformat.py", line 37, in format
pieces.append(force_text(getattr(self, piece)()))
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\encoding.py", line 92, in force_text
s = six.text_type(s)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\functional.py", line 141, in __text_cast
return func(*self.__args, **self.__kw)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\__init__.py", line 84, in ugettext
return _trans.ugettext(message)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\trans_real.py", line 323, in ugettext
return do_translate(message, 'ugettext')
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\trans_real.py", line 300, in do_translate
_default = _default or translation(settings.LANGUAGE_CODE)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\trans_real.py", line 206, in translation
_translations[language] = DjangoTranslation(language)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\trans_real.py", line 116, in __init__
self._add_installed_apps_translations()
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\trans_real.py", line 164, in _add_installed_apps_translations
"The translation infrastructure cannot be initialized before the "
django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.
These are my settings:
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.8.3.
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
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 = 'u%196#-06u3np&!y91km4hp#ufn+80%op1$o5hrqp#c!$y-n-h'
# 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',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = r'C:\inetpub\wwwroot\ZooPythonProject\mysite.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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'default': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': 'logs/mylog.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
'request_handler': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': 'logs/django_request.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': 'DEBUG',
'propagate': True
},
'django.request': {
'handlers': ['request_handler'],
'level': 'DEBUG',
'propagate': False
},
}
}
Does anybody have an idea how to setup this simple django page?
It works if I run it without IIS and Zoo and just do a manage.py runserver, but this is not an option for our production server.
Thanks for your help!
Eve
The problem may (or may not) come from "zoofcgi.py" script. Sorry for inconvenience anyway.
Could you please try a preview release of Zoo v.4 instead: https://github.com/helicontech/zoo/releases It uses different workers for Python application, so your issue may be resolved. Sorry, no documentation yet, but if you already familiar with MS WebPI, then it should be easy to use Zoo for you. After installing it, please, open Applications -> Templates and install "Python sample project". Open it in the browser and there you should find instructions how to put your existing Django project on it.
Sorry, it is still an early beta and applications outside 'Templates' section have not even been tested yet. As I work alone on this project I can't promise fast results, but at least in is open source now and underlying module code that runs applications has not changed significantly, so it is safe to say that if it worked once, then it should work further at least not worse than the previous version.
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'm getting a very strange error that got me really stuck for many hours now.
I did my deploy with Heroku for the first time and am using S3 for Media files. First thing I noticed was that I never had a migration working successfully after installing boto and django-storages-redux, not sure why. Anyway I kept going.
My configurations seemed to be working in AWS, since my staticfiles did go to my bucket the first time I tried it, but I got some img files not coming through, so I decided to reinstall boto and django-registration-redux (to see if it would migrate properly).
In the end it never migrated as expected and now I'm getting the following error:
UnboundLocalError: local variable 'region_name' referenced before assignment
in my BOTO package when collectstatic.
I don't understand why migrate won't work and why I started to get this error when I re-installed boto and django-storages-redux.
terminal:
You have requested to collect static files at the destination
location as specified in your settings.
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 "/Users/Alex/Desktop/Allugare/src/manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle
collected = self.collect()
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect
handler(path, prefixed_path, storage)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 349, in copy_file
if not self.delete_file(path, prefixed_path, source_storage):
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 255, in delete_file
if self.storage.exists(prefixed_path):
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/storages/backends/s3boto.py", line 439, in exists
if self.entries:
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/storages/backends/s3boto.py", line 302, in entries
for entry in self.bucket.list(prefix=self.location))
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/storages/backends/s3boto.py", line 301, in <genexpr>
self._entries = dict((self._decode_name(entry.key), entry)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/s3/bucketlistresultset.py", line 34, in bucket_lister
encoding_type=encoding_type)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/s3/bucket.py", line 473, in get_all_keys
'', headers, **params)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/s3/bucket.py", line 399, in _get_all
query_args=query_args)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/s3/connection.py", line 668, in make_request
retry_handler=retry_handler
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/connection.py", line 1071, in make_request
retry_handler=retry_handler)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/connection.py", line 927, in _mexe
request.authorize(connection=self)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/connection.py", line 377, in authorize
connection._auth_handler.add_auth(self, **kwargs)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/auth.py", line 755, in add_auth
**kwargs)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/auth.py", line 574, in add_auth
string_to_sign = self.string_to_sign(req, canonical_request)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/auth.py", line 514, in string_to_sign
sts.append(self.credential_scope(http_request))
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/auth.py", line 496, in credential_scope
region_name = self.determine_region_name(http_request.host)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/auth.py", line 690, in determine_region_name
return region_name
UnboundLocalError: local variable 'region_name' referenced before assignment
settings.py:
...
INSTALLED_APPS = (
#DJANGO APPS
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
#THIRD PARTY APPS
'allauth',
'allauth.account',
'allauth.socialaccount',
#Social Authentications
'allauth.socialaccount.providers.facebook',
# 'allauth.socialaccount.providers.instagram',
# 'allauth.socialaccount.providers.twitter',
'crispy_forms',
'django_messages',
'storages',
#MY APPS
'lares',
'mensagens',
'profiles',
)
...
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static-live", "static")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "static-live", "media")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
AWS_ACCESS_KEY_ID = "***"
AWS_SECRET_ACCESS_KEY = "***"
AWS_FILE_EXPIRE = 200
AWS_PRELOAD_METADATA = True
AWS_QUERYSTRING_AUTH = True
DEFAULT_FILE_STORAGE = 'allugare.utils.MediaRootS3BotoStorage'
STATICFILES_STORAGE = 'allugare.utils.StaticRootS3BotoStorage'
# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_STORAGE_BUCKET_NAME = 's3allugare'
S3DIRECT_REGION = 'sa-east-1'
S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
MEDIA_ROOT = MEDIA_URL
STATIC_URL = S3_URL + 'static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
AWS_S3_HOST = 'sa-east-1.amazonaws.com'
import datetime
two_months = datetime.timedelta(days=61)
date_two_months_later = datetime.date.today() + two_months
expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT")
AWS_HEADERS = {
'Expires': expires,
'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ),
}
wsgi.py
"""
WSGI config for allugare project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "allugare.settings")
application = get_wsgi_application()
utils.py
from storages.backends.s3boto import S3BotoStorage
StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static') # S3 bucket name -> static
MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media') # S3 bucket name -> static
Okay, here's the thing, if you're not using the default region of AWS you have to be careful when updating your region, since the S3's has different formats depending on the region.
I'm in South America, thus I'm using sa-east-1 (for São Paulo).
To me it worked when I changed the setting:
AWS_S3_HOST = 'sa-east-1.amazonaws.com'
to
AWS_S3_HOST = 's3-sa-east-1.amazonaws.com'
Enjoy!
I've installed Django 1.9.7, and I have Pythons 3.4.3 and 2.7.10 on Ubuntu.
These are the steps I've followed:
Made a new project with django-admin startproject testproject
cd testproject/testproject
Made an app within the project with django-admin startapp testapp
Made a directory for templates in that app with mkdir testapp/templates and added a very basic index.html template in there
Edited settings.py to change the template backend to django.template.backends.jinja2.Jinja2, by editing line 57 of the default settings file, and to add testproject.testapp to INSTALLED_APPS; the TEMPLATES section is therefore like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'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',
],
},
},
]
Edited urls.py, adding from testproject.testapp import views and a URL pattern url(r'^$', views.index),
Edited testapp/views.py adding
def index(request):
return render(request, 'index.html')
cd ..
Ran the server with python3 manage.py runserver, or python manage.py runserver -- very similar effect
Take a browser to http://localhost:3000
I get an error. On the command line I get this:
Internal Server Error: /
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py", line 86, in __getitem__
return self._engines[alias]
KeyError: 'jinja2'
Followed by another exception caused "during handling of the above exception", which matches the exception I see in the browser:
Environment:
Request Method: GET
Request URL: http://localhost:3000/
Django Version: 1.9.7
Python Version: 3.4.3
Installed Applications:
['django.contrib.staticfiles', 'testproject.testapp', 'webpack_loader']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py" in __getitem__
86. return self._engines[alias]
During handling of the above exception ('jinja2'), another exception occurred:
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in get_response
174. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in get_response
172. response = response.render()
File "/usr/local/lib/python3.4/dist-packages/django/template/response.py" in render
160. self.content = self.rendered_content
File "/usr/local/lib/python3.4/dist-packages/django/template/response.py" in rendered_content
135. template = self._resolve_template(self.template_name)
File "/usr/local/lib/python3.4/dist-packages/django/template/response.py" in _resolve_template
90. new_template = self.resolve_template(template)
File "/usr/local/lib/python3.4/dist-packages/django/template/response.py" in resolve_template
80. return select_template(template, using=self.using)
File "/usr/local/lib/python3.4/dist-packages/django/template/loader.py" in select_template
55. engines = _engine_list(using)
File "/usr/local/lib/python3.4/dist-packages/django/template/loader.py" in _engine_list
143. return engines.all() if using is None else [engines[using]]
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py" in all
110. return [self[alias] for alias in self]
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py" in <listcomp>
110. return [self[alias] for alias in self]
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py" in __getitem__
101. engine = engine_cls(params)
File "/usr/local/lib/python3.4/dist-packages/django/template/backends/jinja2.py" in __init__
35. self.env = environment_cls(**options)
Exception Type: TypeError at /
Exception Value: __init__() got an unexpected keyword argument 'context_processors'
I get very similar traces with Python 2.
I found this question which has a similar error message (KeyError: 'jinja2') but seems to be a separate problem, and this bug report which has the same error again whose solution is to install jinja2, but jinja2 is definitely installed. At least, I can run python or python3 and then import jinja2. pip says jinja2 is up to date.
I must be missing something crucial -- any ideas?
The error about context_processors is because the Jinja2 backend does not support that argument.
You should add an additional backend to your TEMPLATES setting, rather than replacing the existing backend from django to jinja2. See this answer for more information. If you replace the existing backend, then apps that require Django templates will not work, including the admin.
Finally, the jinja2 backend will look for templates in testapp/jinja2, not testapp/templates.
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\.