我正在学习 Python/Django/MySQL 三位一体来开发主要使用 Eclipse 的电子商务网站。我已经看到我将要描述的问题在 StackOverflow 和国外互联网上被询问了大约 100 种不同的方式,但似乎每个问题都足够独特,以至于每个解决方案都不适合我。
在 Eclipse 中,我在名为forms.py的文件的开头使用了一些简单的导入语句来导入一些 django 表单和我的个人“产品”类,如下所示:
from django import forms
from ecomstore.catalog.models import Product
问题已经出现了:Eclipse 在行上显示“未解决的导入:产品”警告,引用“产品”。当我运行时:
python manage.py validate
在命令行中,我收到了名义上的错误:“ImportError:没有名为目录的模块”,但我将其命名为_,因为此错误出现在我从目录“模块”的所有导入中。
现在我绝对是 Python 领域的初学者,所以我认为我遗漏了一些明显的东西。在 Eclipse 中,我当然将我的主“ecomstore”目录设置为项目源,据我所知,它将“ecomstore”添加到 PYTHONPATH,从而允许我引用其中的项目。相关目录结构,进一步说明要点:
-ecomstore
---- +manage.py
----其他一些目录
----catalog
------- +models.py
------- +forms.py <--活动文件调用用于导入
----ecomstore <--实际项目文件夹,包含settings.py等
------- +settings.py
对不起,我的术语被关闭了,我仍在从 Java 过渡,学习术语需要一些时间。
我指出我的“项目文件夹”与项目的根文件夹同名,因为我看到了一些同名目录引起的问题,但即使我将根级目录更改为“测试”,导入仍然失败,所以我排除了它,但也许我这样做是错误的。另外,请注意 forms.py 与 models.py 位于同一目录中,这是包含我的“产品”类的文件......这不应该意味着,即使我在 Eclipse 中的源文件夹设置未能添加本身到 PYTHONPATH,导入应该仍然有效,因为 Python 将尝试从“”目录加载,也就是调用导入的那个目录?我确定我的逻辑在某个地方存在缺陷,这就是我来寻求帮助的原因。
如果有帮助,这里是models.py的相关内容,因为问题可能出在我对该文件的设置中,但是,就像我说的那样,这个问题发生在整个项目的多个位置,尽管只有导入来自“目录”。
class Product(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50,
unique=True,
help_text='Unique value for product page URL, created from name.')
brand = models.CharField(max_length=50)
sku = models.CharField(max_length=50)
price = models.DecimalField(max_digits=9,
decimal_places=2,)
old_price = models.DecimalField(max_digits=9,
decimal_places=2,
blank=True,default=0.00)
image = models.CharField(max_length=50)
description = models.TextField()
is_active = models.BooleanField(default=True)
is_bestseller = models.BooleanField(default=False)
is_featured = models.BooleanField(default=False)
meta_keywords = models.CharField("Meta Keywords",
max_length=255,
help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField("Meta Description",
max_length=255,
help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(Auto_now=True)
categories = models.ManyToManyField(Category)
class Meta:
db_table = 'products'
ordering = ['-created_at']
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('catalog_product',(), { 'product_slug': self.slug })
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
编辑 1
我忘了提,我已经尝试从“ecomstore.catalog.models”中删除“ecomstore”,但是,虽然这可以解决 Eclipse 错误,但验证错误保持不变。
编辑 2
我打开了一个命令行并打印了我的 sys.path 以查看正常情况下的内容。通常的 C:\Python27 东西在那里,但没有任何引用 ecomstore ......我认为 manage.db 是为我附加它,因为我使用的书从未告诉我处理 sys.path ......这可能是我的吗错误?“python manage.db validate”究竟是如何知道在我的根 ecomstore 文件夹中查找的?也许凭借它在根文件夹中的位置?
编辑 3
在试图解决问题的所有这些摆弄中,服务器本身完全陷入了“ImportError:没有名为目录的模块”。现在,如果我尝试做任何事情 - 即使只是runserver
,它也会引发错误。
编辑 4
下面是我的 manage.py,位于我的根 ecomstore 目录中。因为它是由 django 创建的,所以我没有对其进行编辑,但我想我会添加它,以防我的 django 安装可能出现异常情况。
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecomstore.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
现在是冗长的settings.py,我在项目工作时当然已经编辑过了。它位于根 ecomstore 项目目录中的 ecomstore 目录中(请参阅上面的目录映射,我现在正在向其中添加 settings.py 文件。
# Django settings for ecomstore 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': 'ecomstore', # Or path to database file if using sqlite3.
### EDITED OUT USER CREDENTIALS FOR STACK OVERFLOW ###
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
import os
#hack to accommodate Windows
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8')).replace('\\', '/')
# 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.
# 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: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
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: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
os.path.join(CURRENT_PATH, 'static'),
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# 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.
# Naturally, edited this out for Stack Overflow as well, never edited it though anyways.
# 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 = 'ecomstore.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'ecomstore.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(CURRENT_PATH, 'templates'),
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'ecomstore.catalog',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'catalog',
# 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,
},
}
}
我相信此时我只编辑了 TEMPLATE_DIRS、STATICFILES_DIRS 和 INSTALLED_APPS,这对每个人来说都应该是显而易见的,但这里仍然存在。
编辑 5
我已经解决了至少部分问题,并隔离了问题。通过从 my中删除ecomstore.catalog
和,我设法让 manage.py 再次正常工作。但是,将这些项目中的任何一个添加回 INSTALLED_APPS 会导致不同的问题。通过重新插入,我得到了. 如果我改为使用,我会收到此错误:catalog
INSTALLED_APPS
ecomstore.catalog
ImportError: No module named catalog
catalog
TypeError: __init__() got an unexpected keyowrd argument 'Auto_now'.
另外,请看下面我的 sys.path,作为初学者,我在设置整个过程时可能会搞砸。
>>> print sys.path
['C:\\Users\\Sean\\Dropbox\\Website\\ecomstore',
'C:\\Python27\\lib\\site-packages\\distribute-0.6.35-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\django_db_log-2.2.1-py2.7.egg',
'C:\\Windows\\system32\\python27.zip',
'C:\\Python27\\DLLs', 'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Users\\Sean\\AppData\\Roaming\\Python\\Python27\\site-packages',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\win32',
'C:\\Python27\\lib\\site-packages\\win32\\lib',
'C:\\Python27\\lib\\site-packages\\Pythonwin']