0
votes

I am new in django. I have two app named comments and newapp.I am trying to import one of Class (Comment Class) from comments app to newapp. But I get an error called

ImportError: cannot import name 'Comment'

Here is my 'model.py' from comments app

from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
# Create your models here.

from newapp.models import NewApp
from newapp.models import Test

class CommentManager(models.Manager):
    def filter_by_instance(self, instance):
        content_type = ContentType.objects.get_for_model(instance.__class__)
        obj_id = instance.id
        qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id)
        return qs



class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    #post = models.ForeignKey(NewApp)

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    objects = CommentManager()

    def __unicode__(self):
        return str(self.user.username)
    def __str__(self):
        return str(self.user.username)

Here is the 'model.py' code for newapp app

from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse

from django.db.models.signals import pre_save
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.utils.text import slugify

#here is the problem code to import below class
from comments.models import Comment


# Create your models here.
class NewApp(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    title = models.CharField(max_length=120)
    slug = models.SlugField(unique=True)
    image = models.FileField(null=True, blank=True)
    content = models.TextField()
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    def _unicode_(self):
        return self.title
    def _str_(self):
        return self.title
    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"slug":self.slug})
    @property
    def comments(self):
        instance = self
        qs = Comment.objects.filter_by_instance(instance)
        return qs    
    # @property
    # def comments(self):
    #   instance = self
    #   qs = Comment.objects.filter_by_instance(instance)
    #     return qs
class Test(models.Model):
    def _unicode_(self):
        return self.title


def create_slug(instance, new_slug=None):
    slug = slugify(instance.title)
    if new_slug is not None:
        slug = new_slug
    qs = NewApp.objects.filter(slug=slug).order_by("-id")
    exists = qs.exists()
    if exists:
        new_slug = "%s-%s" %(slug, qs.first().id)
        return create_slug(instance, new_slug=new_slug)
    return slug


def pre_save_post_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = create_slug(instance)



pre_save.connect(pre_save_post_receiver, sender=NewApp)

INSTALLED APP from setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'posts',
    'comments',
    'newapp',
]

And finnaly i got error like this

Unhandled exception in thread started by <function check_errors.<locals>.wrapper
 at 0x039B27C8>
Traceback (most recent call last):
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\core\management\commands\runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\importlib\__i
nit__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 662, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "C:\Users\eXp\Desktop\venv\mysite\comments\models.py", line 8, in <module
>
    from newapp.models import NewApp
  File "C:\Users\eXp\Desktop\venv\mysite\newapp\models.py", line 13, in <module>

    import django.comments
ImportError: No module named 'django.comments'
Unhandled exception in thread started by <function check_errors.<locals>.wrapper
 at 0x034627C8>
Traceback (most recent call last):
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\core\management\commands\runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\importlib\__i
nit__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 662, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "C:\Users\eXp\Desktop\venv\mysite\comments\models.py", line 8, in <module
>
    from newapp.models import NewApp
  File "C:\Users\eXp\Desktop\venv\mysite\newapp\models.py", line 14, in <module>

    from comments.models import Comment
ImportError: cannot import name 'Comment'
1
It looks like you are going through the "Advancing the Blog" tutorial on CFE. Have you tried looking at the source code for the tutorial? github.com/codingforentrepreneurs/Advancing-the-Blogclick here
yes its "Advancing the Blog" tutorial on CFE youtube channel . thanks for your linkMr. J

1 Answers

0
votes

You're importing newapp from comments and comments from newapp. In python, you can't have circular imports like this. Quick fix: remove the import from newapp inside comments's models.py and replace with a name reference, like this:

class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    post = models.ForeignKey('newapp.NewApp') # <= HERE

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    objects = CommentManager()