获取"没有命名的模块"错误

时间:2014-08-01 17:59:12

标签: python django

编辑:我确实有__init__.py它是在django制作应用时生成的。我只是在目录中添加一个文件。该脚本只是试图from npage.models import Page, Level, Section, Edge,但由于某种奇怪的原因而无法做到这一点:(

编辑2:目录结构+代码片段:

└── npage/ <-- My package?
    ├── __init__.py
    ├── __pycache__/
    │   ├── __init__.cpython-34.pyc
    │   └── models.cpython-34.pyc
    ├── admin.py
    ├── forms.py
    ├── middleware.py
    ├── mixins.py
    ├── models.py <-- My module?
    ├── restructure.py <-- from package.module import classes (Edge,Page, etc.)
    ├── tests.py
    ├── urls.py
    └── views.py

来自restructure.py的代码段,

from npage.models import Edge
import MySQLdb

def ordered_pages_for(level):
    """ return sorted list of pages represented as dictionary objects """
    # the rest of the code just converts a linked list of pages into an Edge set and a table of Pages
# ...
def build_edge_table_of_pages(pagedicts_in_order):
    # prev and next are Page instances (None, 4) where 4 is the first page.pk
    prev0 = None
    for pd in pagedicts_in_order:
        # make a page next=page(pd)
        next0 = page(pd)
        # add an edge prev<-->next    (prev will be None at first)
        e = Edge.create(prev = prev0, next = next0)
        e.save()
        # save prev = next    (now prev is not None, it's a Page.)
        prev0 = next0
    # make edge prev<-->None
    e = Edge.create(prev = prev0, next = None)
    e.save()

我写了一个脚本来将数据库表导入到一个新的django模型定义的结构......

我将脚本放在名为&#39; npage&#39;的应用程序中。 views.py包含from npage.models import *,它运行正常。我的脚本中有相同的行,它位于同一目录中,并且说没有名为npage的结节。我在这里缺少什么?

(env)glitch:npage nathann$ python restructure.py
Traceback (most recent call last):
  File "restructure.py", line 32, in <module>
    from npage.models import * # whhhyyy???
ImportError: No module named npage.models

我尝试进行相对导入,它给了我这个:

Traceback (most recent call last):
  File "restructure.py", line 32, in <module>
    from .models import * # whhhyyy???
ValueError: Attempted relative import in non-package

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。这很简单。

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ipals.settings")

# And abracadabra I can import everything now.
from npage.models import Page, Edge, Level

ipals是我项目的名称。我必须这样做才能识别我的npage应用。请评论这个答案,以便我可以编辑和阐述其工作原理。从我的角度来看,我简单地遇到了环境问题。我的脚本在错误的上下文中执行。