ImportError: cannot import name <model_class>

强颜欢笑 提交于 2019-12-23 21:30:36

问题


I am using forms.ModelChoiceField to have the choice loaded from a specific model entries:

from order.models import Region

class CheckoutForm(forms.Form):
    area = forms.ModelChoiceField(queryset=Region.objects.all(),label=("Area"))

The problem I am facing is that when importing the class name from the app. I get the error:

ImportError: cannot import name Region

Please not that from order.models import Region is working when testing it independently in the shell.

Any Idea what is causing so?

Traceback (most recent call last):
  File "/home/salma/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 92, in inner_run
    self.validate(display_num_errors=True)
  File "/home/salma/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 280, in validate
    num_errors = get_validation_errors(s, app)
  File "/home/salma/venv/local/lib/python2.7/site-packages/django/core/management/validation.py", line 35, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "/home/salma/venv/local/lib/python2.7/site-packages/django/db/models/loading.py", line 166, in get_app_errors
    self._populate()
  File "/home/salma/venv/local/lib/python2.7/site-packages/django/db/models/loading.py", line 75, in _populate
    self.load_app(app_name)
  File "/home/salma/venv/local/lib/python2.7/site-packages/django/db/models/loading.py", line 96, in load_app
    models = import_module('.models', app_name)
  File "/home/salma/venv/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/home/salma/Projects/Morabiz/Saludable/saludable_django/landing/models.py", line 2, in <module>
    from order.models import Dish
  File "/home/salma/Projects/Morabiz/Saludable/saludable_django/order/models.py", line 4, in <module>
    from order.forms import RegistrationFormNoUserName
  File "/home/salma/Projects/Morabiz/Saludable/saludable_django/order/forms.py", line 7, in <module>
    from order.models import Region
ImportError: cannot import name Region

回答1:


As I mentioned in the comments, you have a circular dependency between your forms and models files. You'll either need to refactor to remove the circularity, or if you really can't do that you'll have to move one of the imports into the function where it's used.



来源:https://stackoverflow.com/questions/21142366/importerror-cannot-import-name-model-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!