ImportError: cannot import name <model_class>

14,004

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.

Share:
14,004
Salma Hamed
Author by

Salma Hamed

Updated on June 30, 2022

Comments

  • Salma Hamed
    Salma Hamed almost 2 years

    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
    
  • Joseph Daudi
    Joseph Daudi almost 6 years
    This helped someone out here