Skip to main content
 首页 » 编程设计

python之ImportError:没有名为_______的模块

2025年05月04日9TianFang

我正在学习Python / Django / MySQL三位一体,以主要使用Eclipse开发电子商务站点。我已经看到要描述的问题,在StackOverflow和国外Internet上询问了大约100种不同的方式,但是似乎每个问题都很独特,每个解决方案都不适合我。

在eclipse中,我在名为forms.py的文件的开头使用一些简单的导入语句来导入一些Django表单和我的个人“ Product”类,如下所示:

from django import forms 
from ecomstore.catalog.models import Product 


而且已经出现了问题:Eclipse在行上显示“未解决的导入:产品”警告,引用了“产品”。当我跑步时:

python manage.py validate 


在命令行中,我收到名义上的错误:“ ImportError:未将模块命名为目录”,但我将其命名为_,因为此错误正在从目录“模块”的所有导入中出现。

现在,我绝对是Python领域的初学者,所以我认为我缺少明显的东西。在eclipse中,我当然将我的主“ ecomstore”目录设置为项目源,据我所知,它在PYTHONPATH中添加了“ ecomstore”,因此允许我引用其中的项目。相关的目录结构,以进一步说明要点:

-ecomstore
  ---- + manage.py
  ----其他一些目录
   - - 目录
    ------- + models.py
    ------- + forms.py <-活动文件要求导入
  ---- ecomstore <-实际项目文件夹,包含settings.py等。
    ------- + settings.py

抱歉,我的术语不对,我仍在从Java过渡过来,要花一些时间来学习专业术语。

我指出我的“项目文件夹”与项目的根文件夹具有相同的名称,因为我看到了同名目录引起的一些问题,但是即使在我将根级别目录更改为“测试”之后,导入仍然失败,所以我排除了它,但也许我做错了。另外,请注意,forms.py与models.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”如何确切地知道在我的根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
我至少解决了一部分问题,并隔离了该问题。通过将 ecomstore.catalog和 catalog都从我的 INSTALLED_APPS中删除​​,我设法重新获得了manage.py功能。但是,通过将这些itesm中的任何一个添加回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'] 

请您参考如下方法:

导入时不需要包括ecomstore。您是否已将catalog添加到INSTALLED_APPS项目文件夹中settings.py中的ecomstore中?

例如。:

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', 
    'catalog' 
)