TangoWithDjango | 5.8创建填充脚本|导入错误

时间:2014-05-01 22:42:12

标签: django python-2.7

我目前正在关注http://www.tangowithdjango.com/book/chapters/models.html

在5.8节执行" python manage.py populate_rango.py"我收到了这个错误:

E:\PythonCode\django1\tango_with_django>python populate_rango.py
Starting Rango population script...
Traceback (most recent call last):
   File "populate_rango.py", line 61, in <module>
   from rango.models import Category, Page
  File "E:\PythonCode\django1\tango_with_django\rango\models.py", line 1, in <module>
from django.db import models
  File "C:\python27\lib\site-packages\django\db\models\__init__.py", line 5, in     <module>
    from django.db.models.query import Q
  File "C:\python27\lib\site-packages\django\db\models\query.py", line 17, in <m
odule>
    from django.db.models.deletion import Collector
  File "C:\python27\lib\site-packages\django\db\models\deletion.py", line 4, in
<module>
    from django.db.models import signals, sql
  File "C:\python27\lib\site-packages\django\db\models\sql\__init__.py", line 4,
 in <module>
    from django.db.models.sql.subqueries import *
  File "C:\python27\lib\site-packages\django\db\models\sql\subqueries.py", line
12, in <module>
    from django.db.models.sql.query import Query
  File "C:\python27\lib\site-packages\django\db\models\sql\query.py", line 22, i
n <module>
    from django.db.models.sql import aggregates as base_aggregates_module
  File "C:\python27\lib\site-packages\django\db\models\sql\aggregates.py", line
9, in <module>
    ordinal_aggregate_field = IntegerField()
  File "C:\python27\lib\site-packages\django\db\models\fields\__init__.py", line
 116, in __init__
    self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
  File "C:\python27\lib\site-packages\django\conf\__init__.py", line 54, in __ge
tattr__
    self._setup(name)
  File "C:\python27\lib\site-packages\django\conf\__init__.py", line 49, in _set
up
    self._wrapped = Settings(settings_module)
  File "C:\python27\lib\site-packages\django\conf\__init__.py", line 132, in __i
nit__
    % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'tango_with_django_project.settings' (Is
it on sys.path? Is there an import error in the settings file?): No module named
 tango_with_django_project.settings

Here is the files and directory location E:\PythonCode\django1\tango_with_django>
- manage.py
- populate_rango.py
- tango_with_django [directory]
---- settings.py
---- urls.py
- rango [directory]
---- models.py

models.py

from django.db import models

# Create your models here.

class Category(models.Model):   
    name = models.CharField(max_length=128, unique=True)

    def __unicode__(self):
        return self.name

class Page(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=128)
    url = models.URLField()
    views = models.IntegerField(default=0)

    def __unicode__(self):
        return self.title

populate_rango.py

import os

def populate():
    python_cat = add_cat('Python')

    add_page(cat=python_cat,
        title="Official Python Tutorial",
        url="http://docs.python.org/2/tutorial/")

    add_page(cat=python_cat,
        title="How to Think like a Computer Scientist",
        url="http://www.greenteapress.com/thinkpython/")

    add_page(cat=python_cat,
        title="Learn Python in 10 Minutes",
        url="http://www.korokithakis.net/tutorials/python/")

    django_cat = add_cat("Django")

    add_page(cat=django_cat,
        title="Official Django Tutorial",
        url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")

    add_page(cat=django_cat,
        title="Django Rocks",
        url="http://www.djangorocks.com/")

    add_page(cat=django_cat,
        title="How to Tango with Django",
        url="http://www.tangowithdjango.com/")

    frame_cat = add_cat("Other Frameworks")

    add_page(cat=frame_cat,
        title="Bottle",
        url="http://bottlepy.org/docs/dev/")

    add_page(cat=frame_cat,
        title="Flask",
        url="http://flask.pocoo.org")

    # Print out what we have added to the user.
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print "- {0} - {1}".format(str(c), str(p))

def add_page(cat, title, url, views=0):
    p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]
    p.save()
    return p

def add_cat(name):
    c = Category.objects.get_or_create(name=name)[0]
    c.save()
    return c

# Start execution here!
if __name__ == '__main__':
    print "Starting Rango population script..."
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
    from rango.models import Category, Page
    populate()

settings.py

"""
Django settings for tango_with_django project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
print BASE_DIR
SETTINGS_DIR = os.path.dirname(__file__)

PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates')
TEMPLATE_DIRS = (
    TEMPLATE_PATH,
)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')

DATABASE_PATH = os.path.join(PROJECT_PATH, 'rango.db')


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd!bvy8spg0ij7ok6o9%07*on&$1w#pxm=3+3lazxl@6s=h$yn&'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rango',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'tango_with_django.urls'

WSGI_APPLICATION = 'tango_with_django.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': DATABASE_PATH,
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_PATH = os.path.join(PROJECT_PATH,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    STATIC_PATH,
)

1 个答案:

答案 0 :(得分:3)

您的设置模块的默认路径不正确。您的tango_with_django_project.settings目录为tango_with_django.settings。{/ p>

因此,更改populate_rango.py文件中的第三行到最后一行:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django.settings')