3

I have something like this in one of my apps's models.py :

class Account(AbstractBaseUser):
    email = models.EmailField(unique=True)

I want to import a class from another app's views.py as below:

from anotherapp.views import MyClass

The problem is in the first lines of anotherapp.views file, I imported the Account class. So when I want to import MyClass into my models.py file, this error raises :

ImportError: cannot import name Account
Majid Nayyeri
  • 245
  • 2
  • 11
  • It is a circular import error. Models shouldn't import from views as it is a bad practice. Why would you need MyClass in models? If you still need to, you can put MyClass into some other file, say `utils.py`, then let views and models import from that one. – hurturk Apr 03 '17 at 22:34
  • @hurturk should I put `utils.py` in anotherapp folder or in my current app ? Does it matters at all ? – Majid Nayyeri Apr 03 '17 at 22:46
  • In `anotherapp`, but it doesn't matter as long as it doesn't break your project, you would need to rearrange all imports for `MyClass` depending on the location. – hurturk Apr 03 '17 at 23:18

1 Answers1

2

That is circular import error you are encountering. While it is bad practice to import from views to models in Django, if you still want to, you can follow methods in this question to resolve it.

Here are few alternative ways that can be considered as good practice:

  • You can consider importing other low-level modules exist within anotherapp instead of MyClass (not depending on views.py)
  • You can use Django's signals to catch anotherapp's events project wide and act according to.
  • You can create a third file, say utils.py in anotherapp, move MyClass there and let anotherapp/views.py and your app's models.py import from anotherapp.utils
Community
  • 1
  • 1
hurturk
  • 5,214
  • 24
  • 41