Liondancer
Liondancer

Reputation: 16479

ImportError from different apps

I am importing the models from different apps but I am getting this error and I am not sure why this is occurring.

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 354, in execute
    django.setup()
  File "/Library/Python/2.7/site-packages/django/__init__.py", line 21, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Library/Python/2.7/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/bli1/Development/Django/Spark/users/models.py", line 5, in <module>
    from notifications.models import Notification
  File "/Users/bli1/Development/Django/Spark/notifications/models.py", line 2, in <module>
    from users.models import UserProfile
ImportError: cannot import name UserProfile

my notifications/models:

from django.db import models
from users.models import UserProfile
from restaurants.models import Restaurant

class Notification(models.Model):
    user = models.ForeignKey(UserProfile)
    name = models.CharField(max_length=100)
    about = models.TextField(max_length=1024, blank=True)
    restaurant = models.ForeignKey(Restaurant)

    def __str__(self):
        return self.name

my users/models.py:

from django.db import models
from django.contrib.auth.models import User
from notifications.models import Notification

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    bio = models.TextField(max_length=1024, null=True, blank=True)

Upvotes: 1

Views: 93

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52203

You are the victim of circular import dependency. In order to resolve this, you need to tell Django the import path of the model in ForeignKey instead of actually importing it:

class Notification(models.Model):
    user = models.ForeignKey('users.UserProfile')

Also don't forget to delete import statement from from users.models import UserProfile from notifications/models.py.

Upvotes: 1

levi
levi

Reputation: 22697

You have circular dependencies loop.

User imports Notification and Notification imports User.

Just remove from notifications.models import Notification from your users/models.py

Upvotes: 1

Related Questions