没有名为views django的模块

时间:2013-02-14 11:36:09

标签: django

我是第一次在Windows上开始一个新的django项目。我之前在ubuntu和debian上工作过没有任何问题。但是在Windows上我发现安装它是一件大事。我终于找到了一个安装tutorial,它完美无缺,直到我开始为静态媒体展示方式。我根本找不到使其工作的方法,而不是使用apache的标准django静态媒体处理程序。所以我想我会首先完成页面的其余部分,或至少让它工作。但是当我为view.py制作urls时,它在浏览器中一直说"No module named views.py"。我浏览了互联网并找到了很多解决方案并尝试了它们。我将__init__文件放在视图所在的目录中。然后,我尝试通过在python shell中运行来调试views.py,并提出了这个:

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.`

我终于得到了环境变量mysite.settings,但即便如此它也不起作用,因为它找不到或者不理解它,当我尝试其他一些东西时它又回来了...... 。 我的目录看起来像这样

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 = '&amp;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,
        },
    }
}

所以我无法让一个简单的页面工作,我不知道如何让我的静态文件只是加载apache。非常感谢所有帮助。

EDITTED:

我试过了

  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)

我现在尝试设置环境用户变量,但它似乎删除了自己 然后我运行python.exe manage.py runserver 8000. witch给了我这个错误:

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 个答案:

答案 0 :(得分:1)

1)将settings.py移至C:\wamp\www\

2)export DJANGO_SETTINGS_MODULE = 'settings'

如果您使用的是Windows,则可以输入

set DJANGO_SETTINGS_MODULE = 'settings'

但它只会在你关闭窗口之前有效。

要使其永久化,

a)开始 - >设置 - &gt;控制面板 - &gt;系统或按Win - Pause
b)高级系统设置 - >环境变量 - &gt;新用户变量:
c)(名称)DJANGO_SETTINGS_MODULE,
(值)设置

然后打开新的终端窗口 - 现有窗口不受影响。

3)不要通过运行调试views.py。它通常不起作用。通过

进行调试
python manage.py runserver 8000

当你在C:\wamp\www\内时。