importError: cannot import model name - python-2.7

I am upgrading my django application from django1.5 to django1.11. I know its a huge jump. So I am getting so many errors and try to get it fixed. This is my project structure. I think I have made mistakes in appconfig. I couldn't figure it out.
Now I am stuck on this error.ImportError: cannot import name TrainingProfile
settings.py
INSTALLED_APPS = (
'admin.apps.AdminConfig',
'account.apps.AccountConfig',
'.............'
)
apps/admin/apps.py
class AdminConfig(AppConfig):
name = 'apps.admin'
label = 'admin_app'
apps/account/apps.py
class AccountConfig(AppConfig):
name = 'apps.account'
label = 'account_app'
apps/admin/models/init.py
from apps.admin.models.sector import *
from apps.admin.models.track import *
from apps.admin.models.training import *
...............
traceback
Traceback (most recent call last):
File "/home/sample-applications/upgrade/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "/home/sample-applications/upgrade/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "/home/sample-applications/upgrade/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception
six.reraise(*_exception)
File "/home/sample-applications/upgrade/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "/home/sample-applications/upgrade/venv/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/sample-applications/upgrade/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models()
File "/home/sample-applications/upgrade/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/sample-applications/upgrade/pursuite/django-pursuite/apps/admin/models/__init__.py", line 17, in <module>
from apps.admin.models.job import *
File "/home/sample-applications/upgrade/pursuite/django-pursuite/apps/admin/models/job.py", line 13, in <module>
from account.models import IndustryProfile
File "./apps/account/models.py", line 13, in <module>
from admin.models import Company, Track
File "./apps/admin/models/__init__.py", line 18, in <module>
from apps.admin.models.training import *
File "/home/sample-applications/upgrade/pursuite/django-pursuite/apps/admin/models/training.py", line 12, in <module>
from account.models import TrainingProfile
ImportError: cannot import name TrainingProfile
apps/admin/models/training.py
from django.db import models
from django.contrib import admin
from django.core.urlresolvers import reverse
from tinymce.models import HTMLField
from account.models import TrainingProfile
from analytics.models import State
from admin.common import html2text
__all__ = ['Training']
class Training(models.Model):
'''
Training
'''
class Meta:
'''
Meta properties for this model
'''
app_label = 'admin'
TRAINING_CHOICES = {
('T', 'Trainers'),
('S', 'Students'),
}
training_title = models.CharField(max_length=100, db_index=True)
provider = models.ForeignKey(TrainingProfile, db_index=True)
training_for = models.CharField(max_length=1, choices=TRAINING_CHOICES)
description = HTMLField()
location = models.ForeignKey(State, db_index=True)
create_date = models.DateTimeField(auto_now_add=True)
write_date = models.DateTimeField(auto_now=True)

The relevant part in your traceback is this:
File "/home/sample-applications/upgrade/pursuite/django-pursuite/apps/admin/models/__init__.py", line 17, in <module>
from apps.admin.models.job import *
File "/home/sample-applications/upgrade/pursuite/django-pursuite/apps/admin/models/job.py", line 13, in <module>
from account.models import IndustryProfile
File "./apps/account/models.py", line 13, in <module>
from admin.models import Company, Track
File "./apps/admin/models/__init__.py", line 18, in <module>
from apps.admin.models.training import *
File "/home/sample-applications/upgrade/pursuite/django-pursuite/apps/admin/models/training.py", line 12, in <module>
from account.models import TrainingProfile
ImportError: cannot import name TrainingProfile
From here I see that you are importing admin models from account models (Company and Track) and vice versa (IndustryProfile, TrainingProfile) which is making a circular import. It's very strange that this was working in Django 1.5 at all.
To fix your problem you can check how you are using these models and if the only thing is to put it as argument to models.ForeignKey you can remove the import and use string instead ('account.IndustryProfile', 'account.TrainingProfile', 'admin.Company' and 'admin.Track')
If you can't replace all of them try to replace at least these that will fix your problem.
More info at Django documentation https://docs.djangoproject.com/en/1.11/ref/models/fields/#foreignkey

Your model is in a file named training.py while the file name is not presented in the import at all. It is not in the file structure above neither, so just take a good look at your files and fix your import statement.

Related

While upgrading Django 1.5 to 1.7 throws “Models aren't loaded yet" error

I am upgrading my django application from Django 1.5 to Django 1.7. While upgrading I am getting django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet error. I tried with some solution I got by searching. But nothing is worked for me. I think it because of one of my model. Please help me to fix this.
Traceback (most recent call last):
File "./manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 197, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/venkat/sample-applications/wfmis-django-upgrade/wfmis-upgrade/django-pursuite/apps/admin/models/__init__.py", line 14, in <module>
from occupational_standard import *
File "/home/venkat/sample-applications/wfmis-django-upgrade/wfmis-upgrade/django-pursuite/apps/admin/models/occupational_standard.py", line 160, in <module>
admin.site.register(OccupationalStandard, OccupationalStandardAdmin)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 99, in register
admin_class.check(model)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 153, in check
return cls.checks_class().check(cls, model, **kwargs)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/checks.py", line 497, in check
errors.extend(self._check_list_filter(cls, model))
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/checks.py", line 668, in _check_list_filter
for index, item in enumerate(cls.list_filter)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/checks.py", line 713, in _check_list_filter_item
get_fields_from_path(model, field)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/contrib/admin/utils.py", line 457, in get_fields_from_path
fields.append(parent._meta.get_field_by_name(piece)[0])
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/db/models/options.py", line 416, in get_field_by_name
cache = self.init_name_map()
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/db/models/options.py", line 445, in init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/db/models/options.py", line 563, in get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/db/models/options.py", line 577, in _fill_related_many_to_many_cache
for klass in self.apps.get_models():
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/utils/lru_cache.py", line 101, in wrapper
result = user_function(*args, **kwds)
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 168, in get_models
self.check_models_ready()
File "/home/venkat/sample-applications/wfmis-django-upgrade/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
This is my project strucutre.
setting.py
INSTALLED_APPS = (
'admin.apps.AdminConfig',
'account.apps.AccountConfig',
'...............'
)
wsgi.py
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, '../apps'))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pursuite.settings.production")
import settings
import django.core.management
django.core.management.setup_environ(settings) # Setup settings for core mgmt
utility = django.core.management.ManagementUtility()
command = utility.fetch_command('runserver')
command.validate()
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
apps/admin/apps.py
from django.apps import AppConfig
class AdminConfig(AppConfig):
name = 'apps.admin'
label = 'wfmis_admin'
apps/admin/models/occupational_standard.py
from tinymce.models import HTMLField
from django.db import models
from django.contrib import admin
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from haystack import indexes
from .validators import validate_os_code, validate_version
import admin.common as common
__all__ = ['OccupationalStandard', 'OccupationalStandardIndex']
class OccupationalStandard(models.Model):
'''
Occupational Standard
'''
class Meta:
'''
Meta properties for this model
'''
app_label = 'wfmis_admin'
unique_together = ('code', 'version')
code = models.CharField(
max_length=9, default=None, validators=[validate_os_code],
db_index=True,
)
version = models.CharField(
max_length=8, default=None, validators=[validate_version],
db_index=True,
)
is_draft = models.BooleanField(default=True, verbose_name="Draft")
sub_sector = models.ForeignKey(
'SubSector', db_index=True, verbose_name="Industry Sub-sector",
)
title = models.CharField(
max_length=50, default=None, db_index=True, verbose_name="Unit Title",
)
description = models.TextField(default=None)
scope = HTMLField(default=None)
performace_criteria = HTMLField(default=None)
knowledge = HTMLField(default=None)
skills = HTMLField(default=None)
attachment = models.FileField(upload_to='os_attachments')
drafted_on = models.DateTimeField(auto_now_add=True)
last_reviewed_on = models.DateTimeField(auto_now=True) # Write date
next_review_on = models.DateField()
def __unicode__(self):
'''
Returns object display name. This comprises code and version.
For example: SSC/O2601-V0.1
'''
return "%s-V%s%s (%s)" % (
self.code, self.version, "draft" if self.is_draft else "",
self.title,
)
#property
def sector(self):
"""
Returns sector corresponding to occupational standard.
"""
return self.sub_sector.sector
def get_absolute_url(self):
'''
get absolute url
'''
return reverse('occupational_standard', args=(self.code,))
def clean(self):
'''
Validate model instance
'''
if OccupationalStandard.objects.filter(code=self.code, is_draft=True) \
.exclude(pk=self.pk):
# Check one OS should have one version in draft
raise ValidationError(
'There is already a version in draft for %s' % self.code
)
Reference links : Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
From the traceback I see the following:
File "/home/venkat/sample-applications/wfmis-django-upgrade/wfmis-upgrade/django-pursuite/apps/admin/models/__init__.py", line 14, in <module>
from occupational_standard import *
File "/home/venkat/sample-applications/wfmis-django-upgrade/wfmis-upgrade/django-pursuite/apps/admin/models/occupational_standard.py", line 160, in <module>
admin.site.register(OccupationalStandard, OccupationalStandardAdmin)
There is a call to admin.site.register in the models. Registering models should happen in admin not in models.
Stop the venv before upgrading django.
Stop the server before upgrading.
Update to 1.7 style wsgi handler.
Also, use pip to manage & upgrade packages, your script is bound to break the packages otherwise.

Django AppRegistryNotReady when defining a model

I wanted to add the first model to an already working app, and now I can't start it because it always gives AppRegistryNotReady. This does only happen, if my model MailLog is child of models.Model.
from __future__ import unicode_literals
from django.db import models
#class MailLog(models.Model): # like this, it crashes
class MailLog(): # like this, it works
# Field definitions
recipient = models.EmailField()
created = models.DateTimeField(auto_now_add=True)
template = models.CharField(max_length=500)
error = models.TextField(null=True)
def __str__(self):
return self.recipient+" "+self.template+"("+str(self.created)+")"
The error occurs no matter what's inside the class, even if there is only a pass. However, I can import my models in the admin.py, and it crashes when I import from a file I called core.py. That file looks like this:
import boto3
from botocore.exceptions import ClientError
from django.template import loader
from django.conf import settings
from .templates import *
from .models import MailLog
The traceback looks like this
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute
settings.INSTALLED_APPS
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/home/niels/anaconda3/envs/app/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/niels/Dokumente/jobapp/deploy/backend/settings.py", line 255, in <module>
django.setup()
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/apps/config.py", line 90, in create
module = import_module(entry)
File "/home/niels/anaconda3/envs/app/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/niels/Dokumente/jobapp/deploy/ses_mail/__init__.py", line 1, in <module>
from .core import send
File "/home/niels/Dokumente/jobapp/deploy/ses_mail/core.py", line 7, in <module>
from .admin import MailLog
File "/home/niels/Dokumente/jobapp/deploy/ses_mail/admin.py", line 2, in <module>
from .models import *
File "/home/niels/Dokumente/jobapp/deploy/ses_mail/models.py", line 6, in <module>
class MailLog(models.Model):
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/db/models/base.py", line 105, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
self.check_apps_ready()
File "/home/niels/anaconda3/envs/app/lib/python2.7/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.
You should not be importing Django models in your app's __init__ (or causing them to be imported by importing from core. If you use an empty __init__.py it should stop the error.

User model AttributeError: 'module' object has no attribute 'ForeignKey' [django]

In models
from django.db import models
from django.conf import settings
class Post(ThreadedComment):
author = models.ForeignKey(settings.AUTH_USER_MODEL)
I tried with
from django.db import models
from django.contrib.auth.models import User
class Post(ThreadedComment):
author = models.ForeignKey(User)
Error: when tried to makemigrations
C:\Users\Home\lib\reflect\project\post\models.py:44: RemovedInDjango19Warning: The utilities in django.db.models.loading are deprecated in favor of the new application loading syste
m.
from django.db.models.loading import get_model
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Home\lib\reflect\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line
utility.execute()
File "C:\Users\Home\lib\reflect\lib\site-packages\django\core\management\__init__.py", line 312, in execute
django.setup()
File "C:\Users\Home\lib\reflect\lib\site-packages\django\__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Home\lib\reflect\lib\site-packages\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "C:\Users\Home\lib\reflect\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Python27\Lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\Home\lib\reflect\project\post\models.py", line 62, in <module>
class Post(ThreadedComment):
File "C:\Users\Home\lib\reflect\project\post\models.py", line 65, in Post
author = models.ForeignKey(settings.AUTH_USER_MODEL)
AttributeError: 'module' object has no attribute 'ForeignKey'
ref: https://docs.djangoproject.com/en/1.8/ref/contrib/auth/#django.contrib.auth.models.User
EDIT:
Complete models.py file : http://pastebin.com/tyf9XDE5

Django 1.6b gis import error

I'm using django 1.6b and python 3.3 and I get this import error,
./manage.py runserver
Validating models...
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x104ae4d40>
Traceback (most recent call last):
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/utils/autoreload.py", line 93, in wrapper
fn(*args, **kwargs)
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/core/management/commands/runserver.py", line 97, in inner_run
self.validate(display_num_errors=True)
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/core/management/base.py", line 308, in validate
num_errors = get_validation_errors(s, app)
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/core/management/validation.py", line 34, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/db/models/loading.py", line 196, in get_app_errors
self._populate()
File "/opt/boxen/pyenv/version/side-project/lib/python3.3/site-packages/django/db/models/loading.py", line 78, in _populate
self.load_app(app_name)
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/db/models/loading.py", line 99, in load_app
models = import_module('.models', app_name)
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/moi/Projects/sos/dealerships/models.py", line 4, in <module>
from django.contrib.gis.db import models # as geomodels
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/contrib/gis/db/models/__init__.py", line 8, in <module>
from django.contrib.gis.db.models.manager import GeoManager
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/contrib/gis/db/models/manager.py", line 2, in <module>
from django.contrib.gis.db.models.query import GeoQuerySet
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/contrib/gis/db/models/query.py", line 6, in <module>
from django.contrib.gis.db.models.fields import get_srid_info, PointField, LineStringField
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/contrib/gis/db/models/fields.py", line 4, in <module>
from django.contrib.gis import forms
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/contrib/gis/forms/__init__.py", line 2, in <module>
from .fields import (GeometryField, GeometryCollectionField, PointField,
File "/opt/boxen/pyenv/versions/side-project/lib/python3.3/site-packages/django/contrib/gis/forms/fields.py", line 11, in <module>
from django.contrib.gis.geos import GEOSException, GEOSGeometry, fromstr
ImportError: cannot import name GEOSException
This is the only code I have in place for gis,
from django.contrib.gis.db import models as geomodels
from django.utils.translation import ugettext as _
from django.contrib.localflavor.us.models import USStateField
class UsLocation(geomodels.Model):
address_1 = geomodels.CharField(_("address"), max_length=128)
address_2 = geomodels.CharField(_("address cont'd"), max_length=128, blank=True)
city = geomodels.CharField(_("city"), max_length=64, default="Kansas City")
state = USStateField(_("state"), default="KO")
zip_code = geomodels.CharField(_("zip code"), max_length=5, default="16874")
For now I'm going to not use the gis helpers for my address model but I'm not sure what's causing this import exception. I checked the django 1.5/1.6 releases and they have the same lines. I wonder if it has something to do with me using 1.6b w/ python 3.3.2 ?
Make sure you have installed the Geospatial libraries. I have tested Python 3.3.2 and Django 1.6 beta 2 in a virtual env. The import from contrib.gis works fine.
>>> import django
>>> django.VERSION
(1, 6, 0, 'beta', 2)
>>> from django.contrib.gis.db import models as geomodels
Note that contrib.localflavor has been removed from Django 1.6.
>>> from django.contrib.localflavor.us.models import USStateField
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named 'django.contrib.localflavor'
You can install the django-localflavor package with:
pip install django-localflavor
then change your import to:
from localflavor.us.models import USStateField
I have just faced the same problem. Unfortunately, ImportError: cannot import name GEOSException is not the best error message when Django cannot find GEOS library.
I have Django 1.6.1 final and Python 3.3 too. OS is Windows 7 64-bit. Python, GEOS are x86-64 too.
As recommended at Django docs, the line:
GEOS_LIBRARY_PATH = r'C:\Program Files\OSGeo4W64\bin\geos_c.dll'
in my Django project settings solved this issue.

Circular import is only stopping Django command, not shell or web response

I have two classes which import each other:
profile/models.py
class Company(models.Model):
name = ...
class CompanyReview(models.Model):
company = models.ForeignKey(Company)
from action.models import CompanyAction
action = models.ForeignKey(CompanyAction)
action/models.py
from profile.models import Company
class CompanyAction(models.Model):
company = models.ForeignKey(Company, null = True, blank = True)
The circular import works when the Django app is executed on the server or when I call view functions in the shell. However, when I import one of the classes, Django command will fail with an error (see Traceback below).
Why is that the case and only causing a problem in the command method?
How can I avoid the error? I have tried a lazy import of the CompanyAction class, but it led to the same error message.
not working alternative:
class CompanyReview(models.Model):
company = models.ForeignKey(Company)
from django.db.models import get_model
_model = get_model('action', 'CompanyAction')
action = models.ForeignKey(_model)
Interestingly, the variable _model is empty if I execute my command function and the classes are imported. When I load ./manage.py shell, the variable contains the correct class name. Why is that the case?
Traceback
(virtual-env)PC:neurix$ python manage.py close_action
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line
utility.execute()
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 77, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/Development/project/apps/action/management/commands/close_action.py", line 2, in <module>
from action.models import CompanyAction
File "/Users/Development/project/apps/action/models.py", line 26, in <module>
from profile.models import Company
File "/Users/Development/apps/profile/models.py", line 436, in <module>
class CompanyReview(models.Model):
File "/Users/Development/project/apps/profile/models.py", line 446, in CompanyReview
action = models.ForeignKey(_model)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/db/models/fields/related.py", line 993, in __init__
assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
AssertionError: ForeignKey(None) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
Django has a system for stopping circular imports on foreign keys detailed here: https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
You would want to do something like:
class CompanyReview(models.Model):
company = models.ForeignKey(Company)
action = models.ForeignKey('action.CompanyAction')
class CompanyAction(models.Model):
company = models.ForeignKey('profile.Company', null = True, blank = True)