Cannot import name error in Django split models - python

I have split the Django models into multiple model files following the follow file tree structure,
+-api(app)-+
+-__init__.py
+-models -+
|
+-__init__.py
+-model1.py
+-model2.py
+-model3.py
+-serializers-+
|
+-__init__.py
+- model1_serializer.py
+-views
+-apps.py
...
my __init__.py in models looks like,
from .model1 import *
from .model2 import *
and serializer __init__.py files look like this,
from .model1_serializer import MBTITypeSerializer
I have splitter views files and serializer files. When I try to import models some of them imports without any problem, but some imports not working. I have observed if I change the import order in __init__.py file the working imports change. This is how I tried to import models,
in serializers
from api.models import MBTIType
...
Here is the error trace,
Traceback (most recent call last):
File "C:\Users\ \AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\ \AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "D:\ \implementation\backend\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "D:\\implementation\backend\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
autoreload.raise_last_exception()
File "D:\\implementation\backend\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
raise _exception[1]
File "D:\\implementation\backend\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
autoreload.check_errors(django.setup)()
File "D:\\implementation\backend\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "D:\\implementation\backend\venv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "D:\\implementation\backend\venv\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "D:\\implementation\backend\venv\lib\site-packages\django\apps\config.py", line 301, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\\implementation\backend\api\models\__init__.py", line 2, in <module>
from .model1 import *
File "D:\\implementation\backend\api\models\model1.py", line 3, in <module>
from .model2 import Model2
File "D:\\implementation\backend\api\models\model2.py", line 5, in <module>
from api.serializers import serilizer1
File "D:\\implementation\backend\api\serializers\__init__.py", line 2, in <module>
from .model1_serializer import Model1Serializer
File "D:\\implementation\backend\api\serializers\model1_serializer.py", line 2, in <module>
from api.models import Model1
ImportError: cannot import name 'Model1' from 'api.models' (D:\\implementation\backend\api\models\__init__.py)
Hoping any guidance to solve the issue.

check your model2.py, you have there on line 5 from api.serializers import serilizer1
But you don't need to have serializer1 in models.

Related

How to fix Python circular import error (top level)?

I read about solution for the error (write import instead of from ...) but it doesn't work I think because I have a complex folder structure.
quiz.models
import apps.courses.models as courses_models
courses_models.Lesson # some actions with that class
class Quiz:
pass
courses.models
import apps.quiz.models as quiz_models
quiz_models.Quiz # some actions with that class
class Lesson:
pass
Error:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute
django.setup()
File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/code/apps/carts/models.py", line 5, in <module>
from ..courses.models import Course
File "/code/apps/courses/models.py", line 12, in <module>
import apps.quiz.models as quiz_models
File "/code/apps/quiz/models.py", line 12, in <module>
class Quiz(TimestampedModel):
File "/code/apps/quiz/models.py", line 15, in Quiz
courses_models.Lesson, default=1, on_delete=models.DO_NOTHING, verbose_name=_('Lesson'), related_name='quizzes')
AttributeError: partially initialized module 'apps.courses.models' has no attribute 'Lesson' (most likely due to a circular import)
Maybe you have other solutions for circular importing or I just wrote the imports incorrectly?
Yes, this is a circular import. course.models is importing quiz.models while quiz.models is also importing course.models.
To avoid this, you could defer the import until you really need it.

Error using Textfield and charfield model in Django

I have been trying to use Textfield in class but the suggestions just does not show up. Instead i receive an error in my Cmd console. This was even the case while using CharField.
Below is my code:
from django.db import models
from django.db.models import CharField
from django.db.models import Textfield
from datetime import datetime
class Posts(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
created_at = models.DateTimeField(default=datetime.now, blank=True)
This is the error i get in my CMD:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "d:\python\python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "d:\python\python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\USER\Envs\py1\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\USER\Envs\py1\lib\site-packages\django\core\management\commands\runserver.py", line
109, in inner_run
autoreload.raise_last_exception()
File "C:\Users\USER\Envs\py1\lib\site-packages\django\utils\autoreload.py", line 76, in
raise_last_exception
raise _exception[1]
File "C:\Users\USER\Envs\py1\lib\site-packages\django\core\management\__init__.py", line 357, in
execute
autoreload.check_errors(django.setup)()
File "C:\Users\USER\Envs\py1\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\USER\Envs\py1\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\USER\Envs\py1\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Users\USER\Envs\py1\lib\site-packages\django\apps\config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "d:\python\python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "E:\Python\djangoproject\posts\models.py", line 3, in <module>
from django.db.models import Textfield
ImportError: cannot import name 'Textfield' from 'django.db.models' (C:\Users\USER\Envs\py1\lib\site-
packages\django\db\models\__init__.py)
Actually you don't need to import the fields separately, you could use the django.db.models that you have imported earlier.
And the error is produced because you should use TextField with a capital F

ModuleNotFoundError: No module named 'social.models' when running celery worker

I have the following project structure:
SocialRating
- accounts
-- __init__.py
-- models.py
-- tasks.py
- instagram
-- __init__.py
-- crawler.py
- social
-- __init__.py
-- models.py # Not Django models
- celery_worker.sh
accounts/models.py contains class:
from instagram.crawler import InstagramCrawler
class SocialProfile(models.Model):
...
def collect_profile_stats(self):
crawler = InstagramCrawler()
record_data = crawler.get_profile_stats(self.account_id)
InstagramCrawler class is located in instagram/crawler.py:
from social.models import SocialUserData, SocialCommentData, SocialProfileStatsRecordData
class InstagramCrawler(object):
...
And social/models.py contains simple data classes:
#dataclass
class SocialUserData(object):
user_id: str
#dataclass
class SocialCommentData(object):
social_id: str
user: SocialUserData
text: str
#dataclass
class SocialPostStatsRecordData(object):
post_id: str
subscribers_count: int
likes_count: int
reposts_count: int
comments_count: int
post_date: str
#dataclass
class SocialProfileStatsRecordData(object):
subscribers_count: int
accounts/tasks.py:
#app.task(bind=True)
def update_profile_stats(self, social_profile_pk: int):
social_profile = SocialProfile.objects.get(pk=social_profile_pk)
logger.info(f'Updating profile stats for {social_profile}')
social_profile.collect_profile_stats()
celery_worker.sh:
#!/usr/bin/env bash
celery -A SocialRating worker -l info
So, when I run celery_worker.sh (from project's root directory) it raises:
Signal handler <bound method DjangoFixup.on_import_modules of <celery.fixups.django.DjangoFixup object at 0x106819d30>> raised: ModuleNotFoundError("No module named 'social.models'")
Traceback (most recent call last):
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/utils/dispatch/signal.py", line 288, in send
response = receiver(signal=self, sender=sender, **named)
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/fixups/django.py", line 82, in on_import_modules
self.worker_fixup.validate_models()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/fixups/django.py", line 120, in validate_models
self.django_setup()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/fixups/django.py", line 116, in django_setup
django.setup()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/user/src/python/web/SocialRating/accounts/models.py", line 4, in <module>
from instagram.crawler import InstagramCrawler
File "/Users/user/src/python/web/SocialRating/instagram/crawler.py", line 7, in <module>
from social.models import SocialUserData, SocialCommentData, SocialProfileStatsRecordData
ModuleNotFoundError: No module named 'social.models'
Traceback (most recent call last):
File "/Users/user/src/python/web/SocialRating/.venv/bin/celery", line 10, in <module>
sys.exit(main())
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/__main__.py", line 16, in main
_main()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/bin/celery.py", line 322, in main
cmd.execute_from_commandline(argv)
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline
super(CeleryCommand, self).execute_from_commandline(argv)))
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/bin/base.py", line 275, in execute_from_commandline
return self.handle_argv(self.prog_name, argv[1:])
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/bin/celery.py", line 488, in handle_argv
return self.execute(command, argv)
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/bin/celery.py", line 420, in execute
).run_from_argv(self.prog_name, argv[1:], command=argv[0])
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/bin/worker.py", line 223, in run_from_argv
return self(*args, **options)
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/bin/base.py", line 238, in __call__
ret = self.run(*args, **kwargs)
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/bin/worker.py", line 257, in run
**kwargs)
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/worker/worker.py", line 96, in __init__
self.app.loader.init_worker()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/loaders/base.py", line 114, in init_worker
self.import_default_modules()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/loaders/base.py", line 108, in import_default_modules
raise response
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/utils/dispatch/signal.py", line 288, in send
response = receiver(signal=self, sender=sender, **named)
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/fixups/django.py", line 82, in on_import_modules
self.worker_fixup.validate_models()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/fixups/django.py", line 120, in validate_models
self.django_setup()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/fixups/django.py", line 116, in django_setup
django.setup()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/user/src/python/web/SocialRating/accounts/models.py", line 4, in <module>
from instagram.crawler import InstagramCrawler
File "/Users/user/src/python/web/SocialRating/instagram/crawler.py", line 7, in <module>
from social.models import SocialUserData, SocialCommentData, SocialProfileStatsRecordData
ModuleNotFoundError: No module named 'social.models'
But when I use InstagramCrawler directly from django command, it works fine:
class Command(BaseCommand):
def handle(self, *args, **options):
self.test_account_followers_count()
def test_account_followers_count(self):
crawler = InstagramCrawler()
print(crawler.get_subscribers_count('someacc'))
Why?
It seems as though the social.models module is not being loaded when Celery is run from celery_worker.sh.
Try explicitly setting the PYTHONPATH before running celery_worker.sh. For example:
export PYTHONPATH=.; ./celery_worker.sh

Cannot Import Model Name Django with User Model and Informational Model

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x105de5048>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute
autoreload.check_errors(django.setup)()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/Name/Desktop/ProjectDevCode/Restructured/mysite/seasons/models.py", line 2, in <module>
from users.models import User
File "/Users/Name/Desktop/ProjectDevCode/Restructured/mysite/users/models.py", line 11, in <module>
from seasons.models import Seasons
ImportError: cannot import name 'Seasons'
I randomly got this error in my recent django app. I am not sure why. The models import in other apps/files in my project. Any help is appreciated.
I believe you faced circular model import. Seems like you are importing User into seasons.model and Seasons into users.model.
If you use them as a foreign key you can set it as:
user = models.ForeignKey('users.User')

django Error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet

I am getting an error in Django. I saw a lot of similar questions but am not able to find a working solution. I think the error is in importing the User model. I am not able to find a solution to this. Basically, it seems that it is not able to get the User model. Please help.
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Python34\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
autoreload.raise_last_exception()
File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "C:\Python34\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Python34\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Python34\lib\site-packages\django\apps\registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "C:\Python34\lib\site-packages\django\apps\config.py", line 90, in create
module = import_module(entry)
File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "E:\Python\TheRandomSite\investor\__init__.py", line 1, in <module>
from . import urls
File "E:\Python\TheRandomSite\investor\urls.py", line 18, in <module>
from . import views
File "E:\Python\TheRandomSite\investor\views.py", line 4, in <module>
from investor.models import Game
File "E:\Python\TheRandomSite\investor\models.py", line 3, in <module>
from django.contrib.auth.models import User
File "C:\Python34\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "C:\Python34\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module>
class AbstractBaseUser(models.Model):
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 105, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Python34\lib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config
self.check_apps_ready()
File "C:\Python34\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Thanks.
Try this
Make investor/__init__.py as empty, Then
include('investor.urls')

Categories