我正在学习Python / Django / MySQL三位一体来开发一个主要使用Eclipse的电子商务网站。我已经看到我要描述的问题在StackOverflow和国外的互联网上询问了100种不同的方式,但似乎每个问题都很独特,每个解决方案对我都不起作用。
在eclipse中,我在一个名为 forms.py 的文件的开头使用了一些简单的import语句来导入一些django表单和我的个人“Product”类,如下所示:
from django import forms
from ecomstore.catalog.models import Product
问题已经出现了:Eclipse在线上显示“未解决的导入:产品”警告,引用“产品”。我跑的时候:
python manage.py validate
在命令行中,我收到名义错误:“ImportError:没有名为catalog的模块”,但我将其命名为 _ ,因为我的目录中的所有导入都出现了此错误“模块“。
现在我绝对是Python领域的初学者,所以我想我错过了一些明显的东西。在eclipse中,我当然将我的主要“ecomstore”目录设置为项目源,据我所知,它将“ecomstore”添加到PYTHONPATH,从而允许我引用其中的项目。相关的目录结构,进一步说明要点:
-ecomstore
----的 + manage.py
----其他一些目录
----目录
-------的 + models.py
------- + forms.py < - 调用导入的活动文件
---- ecomstore< - 实际项目文件夹,包含settings.py等。
-------的 + settings.py
很抱歉我的术语已经关闭,我仍在从Java过渡,需要一些时间来学习行话。
我指出我的“项目文件夹”与项目的根文件夹同名,因为我看到了同名目录引起的一些问题,但即使我将根级目录更改为“test”, “进口仍然失败,所以我排除了它,但也许我错了。另外,请注意,forms.py与models.py位于同一目录中,该文件包含我的“Product”类...不应该意味着,即使我在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”究竟如何知道查看我的root ecomstore文件夹?凭借它在根文件夹中的位置或许?
编辑3
在这个试图解决问题的所有这些小问题中,服务器本身完全陷入了“ImportError:No module named catalog”。现在,如果我尝试做任何事情 - 甚至只是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
我已经解决了至少部分问题,并将问题孤立起来。通过从我的ecomstore.catalog
中移除catalog
和INSTALLED_APPS
,我设法再次获得manage.py功能。但是,通过将其中任何一个添加回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']
答案 0 :(得分:1)
导入时无需包含ecomstore
。您是否已将catalog
添加到INSTALLED_APPS
项目文件夹中settings.py
的{{1}}?
E.g:
ecomstore
答案 1 :(得分:0)
将行更改为
from catalog.models import Product
它应该有效。问题是它正在搜索路径上的目录中寻找名为“ecomstore”的模块(目录)。请注意,这与在搜索路径中查找“ecomstore”不同 - 它不关心搜索路径上的目录名称,它只是查看它们内部。
答案 2 :(得分:0)
在黑暗中拍摄:检查Windows系统设置中的PYTHONPATH设置。过去,右键单击“我的电脑”图标,然后单击“属性”。其中一个选项卡将显示系统路径。