eclipse 导入错误:没有名为 _______ 的模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15559965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 20:13:45  来源:igfitidea点击:

ImportError: No module named _______

pythondjangoeclipseimport

提问by fildred13

I'm learning the Python/Django/MySQL trinity to develop an ecommerce site using primarily Eclipse. I've seen the issue I'm about to describe asked about 100 different ways on both StackOverflow and the internet abroad, but it seems every problem is unique enough that each solution doesn't work for me.

我正在学习 Python/Django/MySQL 三位一体来开发一个主要使用 Eclipse 的电子商务网站。我已经看到我将要描述的问题在 StackOverflow 和国外的互联网上被问到了 100 种不同的方式,但似乎每个问题都足够独特,以至于每个解决方案都不适合我。

In eclipse, I'm using some simple import statements at the beginning of a file called forms.pyto import some django forms and my personal "Product" class, like so:

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

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

And already the problem has arose: Eclipse is showing an "Unresolved import: Product" warning on the line, referencing "Product." When I run:

问题已经出现:Eclipse 在线上显示“未解析的导入:产品”警告,引用“产品”。当我运行时:

python manage.py validate

in the command line, I receive the titular error: "ImportError: No module named catalog," but I named it _because this error is cropping up on all of my imports from my catalog "module."

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

Now I am definitely a beginner in the area of Python, so I assume I'm missing something obvious. In eclipse, I have of course set my main "ecomstore" directory to be the project source, which as I understand it adds the "ecomstore" to the PYTHONPATH, thus allowing me to reference items within. The relevant directory structure, to further illustrate the points:

现在我绝对是 Python 领域的初学者,所以我认为我遗漏了一些明显的东西。在 Eclipse 中,我当然已经将我的主“ecomstore”目录设置为项目源,据我所知,它将“ecomstore”添加到 PYTHONPATH,从而允许我引用其中的项目。相关的目录结构,进一步说明几点:

-ecomstore
----+manage.py
----some other directories
----catalog
-------+models.py
-------+forms.py<--active file calling for the import
----ecomstore <--actual project folder, contains settings.py, etc.
-------+settings.py

-ecomstore
---- +manage.py
----一些其他目录
----catalog
------- +models.py
------- +forms.py<--active 文件调用用于导入
----ecomstore <--实际项目文件夹,包含settings.py等
------- +settings.py

Sorry for my terminology being off, I'm still transitioning over from Java and it is taking some time to learn the jargon.

抱歉,我的术语已关闭,我仍在从 Java 过渡,学习术语需要一些时间。

I point out that my "project folder" has the same name as the root folder of the project because I saw a few problems arising from same-named directories, but even after I changed the root-level directory to "test," the import was still failing so I ruled it out, but maybe I was wrong to do so. Also, notice that forms.py is in the same directory as models.py, which is the file that contains my "Product" class...shouldn't that mean that, even IF my source folder setup in Eclipse was failing to add itself to PYTHONPATH, the import should STILL work because Python will try to load from the "" directory, aka the one from which the import is being called? I'm sure my logic is flawed somewhere, which is why I've come asking for help.

我指出我的“项目文件夹”与项目的根文件夹同名,因为我看到同名目录引起的一些问题,但即使将根级目录更改为“test”,导入仍然失败,所以我排除了它,但也许我这样做是错误的。另外,请注意,forms.py 与models.py 位于同一目录中,该文件包含我的“产品”类......这不应该意味着,即使我在 Eclipse 中设置的源文件夹未能添加本身到 PYTHONPATH,导入应该仍然有效,因为 Python 将尝试从 "" 目录加载,也就是调用导入的目录?我确信我的逻辑在某处存在缺陷,这就是我来寻求帮助的原因。

In case it will help, here is the relevant contents of models.py, because maybe the problem is in my setup of that file instead, though, like I said, this problem is occurring in several location throughout the project, though ONLY with imports from "catalog."

如果有帮助,这里是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

EDIT 1
I forgot to mention, I have tried removing "ecomstore" from "ecomstore.catalog.models" but, while that cures the Eclipse error, the validation error remains the same.

编辑 1
我忘了提及,我曾尝试从“ecomstore.catalog.models”中删除“ecomstore”,但是,虽然这解决了 Eclipse 错误,但验证错误仍然相同。

EDIT 2
I opened up a command line and printed my sys.path to see what was in there normally. The usual C:\Python27 things were there, but nothing referencing ecomstore...I assumed manage.db was appending it for me, since the book I am using never told me to deal with sys.path...is this possibly my error? How exactly does "python manage.db validate" know to look in my root ecomstore folder? By virtue of its location in the root folder perhaps?

编辑 2
我打开一个命令行并打印我的 sys.path 以查看那里通常有什么。通常的 C:\Python27 东西在那里,但没有任何引用 ecomstore...我认为 manage.db 是为我附加它,因为我使用的书从未告诉我处理 sys.path...这可能是我的错误?“python manage.db validate”究竟是如何知道在我的根 ecomstore 文件夹中查找的?也许是因为它在根文件夹中的位置?

EDIT 3
Somewhere in all this fiddling attempting to fix the problem, the server itself got completely caught on the "ImportError: No module named catalog." Now if I try to do ANYTHING - even so much as just runserver, it throws the error.

编辑 3
在试图解决问题的所有这些摆弄中的某个地方,服务器本身完全陷入了“导入错误:没有名为目录的模块”。现在,如果我尝试做任何事情 - 即使是 just runserver,它也会抛出错误。

EDIT 4
Below is my manage.py, located in my root ecomstore directory. I have left it unedited since it was created by django, but I figure I'll add it in case there is something unusual with my django installation perhaps.

编辑 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)

And now, the lengthy settings.py, which I have of course edited while working on the project. This is located in the ecomstore directory WITHIN the root ecomstore project directory (see the above directory map, which I am now adding the settings.py file to.

现在,冗长的 settings.py,我当然在项目工作时编辑过。它位于根 ecomstore 项目目录中的 ecomstore 目录中(请参阅上面的目录映射,我现在正在向其中添加 settings.py 文件。

# Django settings for ecomstore project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', '[email protected]'),
)

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 clickHymaning protection:
    # 'django.middleware.clickHymaning.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,
        },
    }
}

I believe I have only edited TEMPLATE_DIRS, STATICFILES_DIRS, and INSTALLED_APPS at this point, as should be plainly obvious to everyone, but here it all is nevertheless.

我相信此时我只编辑了 TEMPLATE_DIRS、STATICFILES_DIRS 和 INSTALLED_APPS,这对每个人来说都应该是显而易见的,但这里仍然如此。

EDIT 5
I have solved at least part of the problem, and isolated the issue. By removing both ecomstore.catalogand catalogfrom my INSTALLED_APPS, I've managed to get manage.py functional again. However, by adding either of those itesm back to INSTALLED_APPS causes different problems. By reinserting ecomstore.catalogI get the ImportError: No module named catalog. If I instead use catalog, I get this error: TypeError: __init__() got an unexpected keyowrd argument 'Auto_now'.

编辑 5
我至少解决了部分问题,并隔离了问题。通过从 my 中删除ecomstore.catalog和,我已经设法使 manage.py 再次发挥作用。但是,通过将这些项目中的任何一个添加回 INSTALLED_APPS 会导致不同的问题。通过重新插入,我得到了. 如果我改为使用,则会收到此错误:catalogINSTALLED_APPSecomstore.catalogImportError: No module named catalogcatalogTypeError: __init__() got an unexpected keyowrd argument 'Auto_now'.

In addition, see below my sys.path, which being the beginner I am I may have bungled when setting the whole thing up in the first place.

此外,请参阅下面我的 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']

采纳答案by Ric

You do not need to include ecomstorewhen importing. Have you added catalogto your INSTALLED_APPSin your settings.pyin the ecomstoreproject folder?

ecomstore导入时不需要包含。您已经添加catalog到您INSTALLED_APPS在您settings.pyecomstore项目文件夹?

E.g.:

例如:

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

回答by n3storm

Shot in the dark: Check your PYTHONPATH settings in Windows System Settings. It used to be right clicking over the My PC icon and click on Properties. One of the tabs will show you sistem paths.

在黑暗中拍摄:检查 Windows 系统设置中的 PYTHONPATH 设置。它曾经是右键单击“我的电脑”图标并单击“属性”。其中一个选项卡将显示系统路径。

回答by lxop

Change the line to

将行更改为

from catalog.models import Product

and it should work. The problem is it is looking for a module (directory) named 'ecomstore' within the directories on the search path. Note that this is different to finding 'ecomstore' in the search path - it doesn't care what the directory names on the search path are, it just looks inside them.

它应该工作。问题是它正在搜索路径上的目录中寻找名为“ecomstore”的模块(目录)。请注意,这与在搜索路径中查找 'ecomstore' 不同 - 它不关心搜索路径上的目录名称是什么,它只在其中查找。