Django无法导入模型

wjd*_*jdp 2 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())
Run Code Online (Sandbox Code Playgroud)

这给出了错误:

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'
Run Code Online (Sandbox Code Playgroud)

但是,使用shell证明存在模型:

>>> import xsd_training.models
>>> xsd_training.models.Lesson.objects.all()
[<Lesson...
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

Dan*_*man 5

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

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