Django无法导入模型

时间:2014-11-20 14:36:08

标签: django django-models

我在xsd_messages/forms.py

中有以下内容
import xsd_training.models

class UpdateRequestForm(forms.Form):
    lesson = forms.ModelChoiceField(
        queryset=xsd_training.models.Lesson.objects.all())

这给出了错误:

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/will/env/xSACdb/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/home/will/env/xSACdb/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
    django.setup()
  File "/home/will/env/xSACdb/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/will/env/xSACdb/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/home/will/env/xSACdb/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/will/local/xSACdb/xsd_members/models.py", line 6, in <module>
    from xsd_training.models import PerformedLesson
  File "/home/will/local/xSACdb/xsd_training/models.py", line 8, in <module>
    import xsd_messages.views
  File "/home/will/local/xSACdb/xsd_messages/views.py", line 15, in <module>
    from xsd_messages.forms import MailingComposeForm, UpdateRequestForm
  File "/home/will/local/xSACdb/xsd_messages/forms.py", line 14, in <module>
    class UpdateRequestForm(forms.Form):
  File "/home/will/local/xSACdb/xsd_messages/forms.py", line 26, in UpdateRequestForm
    queryset=xsd_training.models.Lesson.objects.all())
AttributeError: 'module' object has no attribute 'models'

然而,使用shell证明存在模型:

>>> import xsd_training.models
>>> xsd_training.models.Lesson.objects.all()
[<Lesson...

发生了什么事?

2 个答案:

答案 0 :(得分:5)

你有一个循环引用:members.models导入training.models,它导入messages.views,导入mesages.forms,导入training.models ......循环无法解析,所以Python报告错误。

你需要打破这个链条。在没有看到代码的情况下,我无法帮助你,但是模型文件导入视图文件是非常可疑的:真的不应该发生。

答案 1 :(得分:0)

import xsd_messages.views中的xsd_training.models移至函数内而不是文件顶部。