Import app model class in another app model - django

I got 2 app: coworkers and services, each one with its own models.py
In coworkers models.py, I can "from services.models import Services".
When I try to "from coworkers.models import Status" in services models.py, I get this error message:
Traceback (most recent call last): File
"/Users/lucas/Documents/projetos/cwk-manager/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/core/management/commands/runserver.py",
line 91, in inner_run
self.validate(display_num_errors=True) File "/Users/lucas/Documents/projetos/cwk-manager/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/core/management/base.py",
line 266, in validate
num_errors = get_validation_errors(s, app) File "/Users/lucas/Documents/projetos/cwk-manager/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/core/management/validation.py",
line 30, in get_validation_errors
for (app_name, error) in get_app_errors().items(): File "/Users/lucas/Documents/projetos/cwk-manager/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/db/models/loading.py", line 158, in get_app_errors
self._populate() File "/Users/lucas/Documents/projetos/cwk-manager/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/db/models/loading.py", line 64, in _populate
self.load_app(app_name, True) File "/Users/lucas/Documents/projetos/cwk-manager/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/db/models/loading.py", line 88, in load_app
models = import_module('.models', app_name) File "/Users/lucas/Documents/projetos/cwk-manager/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/utils/importlib.py",
line 35, in import_module
import(name) File "/Users/lucas/Documents/projetos/cwk-manager/cwk-manager/cwk_manager/coworkers/models.py",
line 2, in
from services.models import Services File "/Users/lucas/Documents/projetos/cwk-manager/cwk-manager/cwk_manager/services/models.py",
line 5, in
class Services(models.Model): File "/Users/lucas/Documents/projetos/cwk-manager/cwk-manager/cwk_manager/services/models.py",
line 11, in Services
status = models.ForeignKey(Status) NameError: name 'Status' is not defined
--
coworker models.py
from django.db import models
from services.models import Services
class Status(models.Model):
status_name = models.CharField(max_length=50)
status_description = models.TextField(blank=True, null=True)
class Meta:
verbose_name = "Status"
verbose_name_plural = "Status"
def __unicode__(self):
return self.status_name
services models.py
from django.db import models
from coworkers.models import Status
# This table contains all the information about plans and other general services provided.
class Services(models.Model):
service_name = models.CharField(max_length=100)
service_description = models.TextField(blank=True, null=True)
service_price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True)
creation_date = models.DateField(auto_now_add=True)
last_update = models.DateField(auto_now=True)
status = models.ForeignKey(Status)
class Meta:
verbose_name = "Services"
verbose_name_plural = "Services"
def __unicode__(self):
return self.service_name
--
Can someone help me to see what I am doing wrong?
Thanks in advance!

This is caused by circular import in Python.
You can use this syntax:
status = models.ForeignKey('coworkers.models.Status')
Django will determine model using this path so you don't need to import Status.
Another solution in your case would be to delete 2nd import statement in coworker.models because Services doesn't seem to be used in this file.

In Django 1.6.5 this:
import coworkers
status = models.ForeignKey(coworkers.models.Status)
Should be this:
import coworkers
status = models.ForeignKey(coworkers.Status)
I am (now) aware the the OP is using Django 1.4.3 and that some of the answers may solve this in that version of Django. However, it took me a while to notice the version and those answers do not work in 1.6.5.
Cheers!

It's circularly import, which results errors.
You can try,
import coworkers
status = models.ForeignKey(coworkers.models.Status)

Just create the Status model first and do syncdb and after that create the services model and syncdb. It should work.
The problem is that python is not ab le to find the 'Status' coz its first trying to create the Services model.

I got all sorts of errors like this while doing syncdb:
CommandError: One or more models did not validate: parts.vehicle:
'customer' has a relation with model <class
'customers.models.Customer'>, which has either not been installed or
is abstract.
I finally realized I had forgotten to add the new app to settings.py. Admin couldn't find it either. That should have been my first clue. Otherwise I was doing what was in the answer by e.thompsy for django 1.6.5

Related

How to import export works in foreign key - django

I do have two models 1) patient profile, to get patient First and last name, default id and 2) Medinfo, medical information of patient used default id of patient model as foreign key.
I am trying to use django import export for bulk upload data.. in patient profile model i can able to upload data without any trouble, but when I trying upload data in medinfo model, I am getting error. I do understand due to using foreinkey as field I am getting trouble here to import data. How to do it?
Note: pat_ID is also a primary key of Medinfo model.
class Patientprofile(models.Model):
pat_Fname = models.CharField(max_length=100)
pat_Lname = models.CharField(max_length=100, blank=True)
def __str__(self):
return str(self.id)
class MedInfo(models.Model):
# Medical Information fields
Notes = models.TextField(max_length=2000, blank=True)
pat_ID = models.OneToOneField(patientprofile, on_delete=models.CASCADE,unique=True, primary_key=True)
def __int__(self):
return self.pat_ID
Error:
Line number: 1 - 'id'
, 32.0
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 661, in import_row
instance, new = self.get_or_init_instance(instance_loader, row)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 353, in get_or_init_instance
instance = self.get_instance(instance_loader, row)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 340, in get_instance
import_id_fields = [
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 341, in <listcomp>
self.fields[f] for f in self.get_import_id_fields()
KeyError: 'id'

System check identified 3 issues (0 silenced)

what could the issue with my model.py .i have tried everything nothing happens.and i think i defined my foreign key the right way .could it be a problem with my defining or do i have to use memberid.user in my foreginkey or what would be effect.any contribution is welcomed.
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x7f6a926d69b0>
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
self.check(display_num_errors=True)
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 405, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
tithe.tithe.memberid: (fields.E300) Field defines a relation with model 'memberid', which is either not installed, or is abstract.
tithe.tithe.memberid: (fields.E307) The field tithe.tithe.memberid was declared with a lazy reference to 'tithe.memberid', but app 'tithe' doesn't provide model 'memberid'.
tithe.tithe: (models.E012) 'unique_together' refers to the non-existent field 'IntegerField'.
System check identified 3 issues (0 silenced).
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x7f3d3ccdc9b0>
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
self.check(display_num_errors=True)
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 405, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
tithe.tithe.memberid: (fields.E300) Field defines a relation with model 'User', which is either not installed, or is abstract.
tithe.tithe.memberid: (fields.E307) The field tithe.tithe.memberid was declared with a lazy reference to 'tithe.user', but app 'tithe' doesn't provide model 'user'.
tithe.tithe: (models.E012) 'unique_together' refers to the non-existent field 'IntegerField'.
this my model.py code
from django.utils import timezone
from django.db import models
# Create your models here.
class tithe(models.Model):
memberid = models.ForeignKey('User')
membername = models.CharField(max_length=45)
receitcode = models.CharField(max_length=45)
tithes = models.IntegerField()
combinedoffering = models.IntegerField()
campmeetingoffering = models.IntegerField()
churchbuilding = models.IntegerField()
conference = models.IntegerField()
localchurch = models.IntegerField()
funds = models.IntegerField()
total = models.IntegerField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.receitcode
class Meta:
unique_together = ["receitcode","IntegerField"]
ordering = ["published_date","membername"]
The line below
memberid = models.ForeignKey('User')
is causing the problem. You have to pass a User object to it.
Import User model.
from django.contrib.auth.models import User
then
memberid = models.ForeignKey(User)
The first two warnings are because Django cannot find the model 'User' that you refer to in the memberid foreign key.
I recommend you use settings.AUTH_USER_MODEL to reference the user model. This will work whether or not you have a custom user model.
memberid = models.ForeignKey(settings.AUTH_USER_MODEL)
See the docs for more info on referencing the user model.
Note that it would be better to call name your field member. That way, the related instance will be member and the related id will be member_id. At the moment, the related instance is memberid, and the related id is memberid_id.
The final warning is because you do not have a field IntegerField in the model. If you want the receitcode field to be unique by itself, then remove the unique_together line and change the field to:
receitcode = models.CharField(max_length=45, unique=True)
Your ForeignKey needs to reference a concrete model or abstract model. Since you are referencing using a string (which means the model is abstract) you need to declare the class Meta: as abstract by stating abstract = True
Relationships defined this way on abstract models are resolved when the model is subclassed as a concrete model and are not relative to the abstract model’s app_label:
The below information is from the Django Documentation https://docs.djangoproject.com/en/1.11/ref/models/fields/
products/models.py
from django.db import models
class AbstractCar(models.Model):
manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)
# This is what you need to add
class Meta:
abstract = True

Django 1.8 and nose: conflicting models?

I have a Django application I recently upgraded to Django 1.8.4. I'm using nose 1.3.7 and django-nose 1.4.1 for my test runner to run over 200 integration and unit tests. Since upgrading both Django and nose, I'm finding that 12 of my tests fail with this same error:
======================================================================
ERROR: Failure: RuntimeError (Conflicting 'c' models in application 'nose': <class 'account.tests.form_tests.TestAddress'> and <class 'nose.util.C'>.)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/me/venv/myproj/lib/python2.7/site-packages/nose/loader.py", line 523, in makeTest
return self._makeTest(obj, parent)
File "/Users/me/venv/myproj/lib/python2.7/site-packages/nose/loader.py", line 568, in _makeTest
obj = transplant_class(obj, parent.__name__)
File "/Users/me/venv/myproj/lib/python2.7/site-packages/nose/util.py", line 644, in transplant_class
class C(cls):
File "/Users/me/venv/myproj/lib/python2.7/site-packages/django/db/models/base.py", line 311, in __new__
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
File "/Users/me/venv/myproj/lib/python2.7/site-packages/django/apps/registry.py", line 223, in register_model
(model_name, app_label, app_models[model_name], model))
RuntimeError: Conflicting 'c' models in application 'nose': <class 'account.tests.form_tests.TestAddress'> and <class 'nose.util.C'>.
What's curious is that the form_tests.py module doesn't even reference TestAddress which is actually a class inside my "profiles" model:
# myprof/profile/models.py
class TestAddress(models.Model):
user = models.OneToOneField(User, primary_key=True, unique=True)
address_line_1 = models.CharField(max_length=30)
address_line_2 = models.CharField(max_length=30, null=True, blank=True)
city = models.CharField(max_length=30)
region = models.CharField(max_length=30, null=True, blank=True)
postal_code = models.CharField(max_length=10, null=True, blank=True)
country = models.ForeignKey('Country')
class Meta:
db_table = 'test_address'
def __unicode__(self):
return u'%s' % (self.user.username)
When my tests need to generate an instance of the TestAddress class, I use a factory_boy (v. 2.5.2) factory:
# utils/factories.py
from profile.models import TestAddress
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
username = 'testuser'
class TestAddressFactory(factory.django.DjangoModelFactory):
class Meta:
model = TestAddress
user = factory.SubFactory('utils.factories.UserFactory')
address_line_1 = '123 Main St.'
address_line_2 = 'Apt. A'
city = 'AnyCity'
region = 'AnyRegion'
postal_code = '12345'
country = factory.SubFactory('utils.factories.CountryFactory')
I set breakpoints in the nose loader.py module and confirmed that loader sees "TestAddress" in "profile.models". However, there is a "parent.__name__" variable there which is set to "account.tests.model_tests". I have a couple of questions:
1. Why is this occurring?
2. Is there a way I can fix it?
3. Is there some way I can get nose to tell me which tests are resulting in these runtime errors so that I can at least disable them if I can't fix the problem?
I set "--verbosity=2" but that
doesn't display the names of failing tests. I looked through the nose docs and didn't see anything. Worst case I can write a script to call every test individually and echo the test name before running it but that seems very ugly and time-consuming.
Thanks.
I ran into the same issue while porting my Django project from 1.6 to 1.8 and updating django-nose to 1.4.3.
It appears that with the new DiscoverRunner used in 1.7 onwards, django-nose attempts to run all classes beginning with Test* as Test Cases, which leads to them being adapted into django-nose's django app before they are encountered in test modules.
I managed to resolve this issue by renaming them to avoid this naming scheme, to things like AdressTestModel.
I just encountered this and solved it with the #nottest decorator.
Technically, it's for functions according to the docs, but decorating classes with it also works:
from nose.tools import nottest
#nottest
class TestAddressFactory(...):
...
All the decorator does is add __test__ with the value True to the object it is decorating.
def nottest(func):
"""Decorator to mark a function or method as *not* a test
"""
func.__test__ = False
return func

Get and set ForeignKey directly in Django

I'm trying to work with Django model created from a mysql database which has composite foreign keys.
My models.py goes like this.
class Make(models.Model):
idmake = models.IntegerField(primary_key=True)
make = models.CharField(max_length=20L, unique=True, blank=True)
def __unicode__(self):
return self.make
class Meta:
db_table = 'make'
class Models(models.Model):
idmodels = models.IntegerField(primary_key=True, unique=True)
make = models.ForeignKey(Make, db_column='make', to_field='make')
model = models.CharField(max_length=45L, unique=True)
resource_type = models.CharField(max_length=7L)
def __unicode__(self):
return self.model
class Meta:
db_table = 'models'
class Systems(models.Model):
idsystems = models.IntegerField(primary_key=True, unique=True)
make = models.ForeignKey(Models, null=True, db_column='make', blank=True, related_name='system_make')
model = models.ForeignKey(Models, null=True, db_column='model', to_field = 'model', blank=True, related_name='system_model')
serial_num = models.CharField(max_length=45L, blank=True)
service_tag = models.CharField(max_length=45L, blank=True)
mac = models.CharField(max_length=45L, unique=True)
Now when I try to access the make field of Systems I get a ValueError.
>>> s = Systems.objects.get(pk=1)
>>> s.model
<Models: model11>
>>> s.model.make
<Make: make1>
>>> s.make
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/django/db/models/fields/related.py", line 384, in __get__
rel_obj = qs.get(**params)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 395, in get
clone = self.filter(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 669, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 687, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1271, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1202, in add_filter
connector)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/where.py", line 71, in add
value = obj.prepare(lookup_type, value)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/where.py", line 339, in prepare
return self.field.get_prep_lookup(lookup_type, value)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1003, in get_prep_lookup
return super(IntegerField, self).get_prep_lookup(lookup_type, value)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 322, in get_prep_lookup
return self.get_prep_value(value)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 997, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'make1'
I'm not allowed to change the tables and relations in the database. I'm very new to Django and I'm unable to figure out what is the correct fix for this issue. Basically I would like to be able to get and set the make field of the Systems model directly. Can someone guide me on how I should go about doing this? My initial thoughts were that I would have to create a custom ForeignKey field.
I suspect your codes don't match your DB schema. In this line:
make = models.ForeignKey(Models, null=True, db_column='make', blank=True, related_name='system_make')
Models is supposed to be Make, isn't it? And your Systems.model has to_field = 'model', did you miss to_field='make' for Systems.make? I suggest you to drop the whole DB, run syncdb and create test data again. Then see if the error still happen.
Some more tips for your code:
as your defined to_field = 'model' and to_field='make', you'd better to consider add db_index=True for make and model fields. Otherwise query performance may be bad when your dataset is large
if you're going to set Make.make and Models.model to be unique and indexed, they seems to be qualified as primary key. Are the idmake and idmodels really necessary in your case?
primary_key=True guarantees unique. unique=True is redundant
Django conversions use singular form for model definition. I.e., use Model System, rather than Models Systems. Also, usually we use id, rather than idmake, idmodels. Those are just conversions, up to you
I discovered the answer, rather by accident. Would like to share for anyone facing similar problem.
To access make directly from Systems
>>> s = Systems.objects.get(pk=1)
>>> s.model
<Models: model11>
>>> s.model.make
<Make: make1>
>>> s.make_id
u'make1'
To set make directly from a Systems object
>>> s.make_id = Models.objects.get(model='model21').make.make
>>> s.save()
>>> s.make_id
u'make2'
Be warned. This will not work if the get method of Models returns multiple or no model objects. For example if my Models table was as:
then
>>>> Models.objects.get(model='unknown').make.make
Traceback (most recent call last):
....
MultipleObjectsReturned: get() returned more than one Models -- it returned 2!
>>> Models.objects.get(model='not known').make.make
Traceback (most recent call last):
....
DoesNotExist: Models matching query does not exist.
I fell the programmer needs to be cautious about these things.
EDIT
From comments by #ZZY to this answer and to his own answer
class Models(models.Model):
idmodels = models.IntegerField(primary_key=True, unique=True)
make = models.ForeignKey(Make, db_column='make', to_field='make')
model = models.CharField(max_length=45L, unique=True)
resource_type = models.CharField(max_length=7L)
def __unicode__(self):
return self.model
class Meta:
db_table = 'models'
unique_together = ("make", "model")
And also since model field in Models is unique, the scenario described by me should not occur in a correct table

Select field for all models within a Django app

I am pretty new to Django.
I wanted to create a form for some user information. Depending on type of user informations, the fields should change... For example the users private address needs the fields name, street, zip and city. But if he wants something send to the company, there might be more fields like department or company name.
I want to implement something like this and create for each kind of input an extra model compact in a separate app.
Is there a way to get a select field with a list of all available models in this app.
Edit
Since I have some further problems, I add an example here
file: experiment/models.py
from django.db import models
from django.apps import apps
class BasicExperiment(models.Model):
date_created = models.DateTimeField(editable=False)
date_modified = models.DateTimeField(blank=True)
label_app = apps.get_app('labels')
label_types = apps.get_models(label_app)
file: labels/models.py
from django.db import models
class SILAC(models.Model):
lys0 = models.BooleanField('Lys-0', default=True)
lys4 = models.BooleanField('Lys-4', default=None)
lys8 = models.BooleanField('Lys-8', default=None)
arg0 = models.BooleanField('Arg-0', default=True)
arg6 = models.BooleanField('Arg-6', default=None)
arg10 = models.BooleanField('Arg-10', default=None)
class Meta:
verbose_name = 'SILAC Labeling'
In the shell it works as expected:
>>> from django.apps import apps
>>> app = apps.get_app('labels')
>>> for model in apps.get_models(app):
... model._meta.verbose_name
...
'SILAC Labeling'
Within my models.py I get the following error:
...
File "/Users/madejung/Documents/django_dev/cfproteomics/experiments/models.py", line 5, in <module>
class BasicExperiment(models.Model):
File "/Users/madejung/Documents/django_dev/cfproteomics/experiments/models.py", line 10, in BasicExperiment
label_app = apps.get_app('labels')
File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 370, in get_app
"App '%s' doesn't have a models module." % app_label)
django.core.exceptions.ImproperlyConfigured: App 'labels' doesn't have a models module.
You could try this:
from django.db.models import get_app, get_models
app = get_app('my_application_name')
for model in get_models(app):
# do something with the model
Here there is more information Django get list of models in application