Can a manager's get_queryset function query across relationships? - django

I'm trying to use a custom Manager class to limit the queryset when accessing objects from a model. But I'd like to limit the queryset with fields from a related model, something like
class MyManager(models.Manager):
def get_queryset(self):
return super(MyManager, self).get_queryset().filter(user__is_active=True)
class MyModel(models.Model):
objects = MyManager()
user = models.OneToOneField(settings.AUTH_USER_MODEL)
But the AppRegistry complains, saying that models aren't loaded yet, which I assume to mean the cross query with user in get_queryset, even though the django.contrib.auth app is being loaded before this app. What's going on?
EDIT: Traceback (see the line where it says user__groups__name=GROUP_MEMBER)
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 198, 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 "/vagrant/members_only/base/models.py", line 255, in <module>
from base.settings import PAGE_NAME_TO_VIEW
File "/vagrant/members_only/base/settings.py", line 4, in <module>
from shb.views import *
File "/vagrant/members_only/shb/views.py", line 10, in <module>
from shb.forms import *
File "/vagrant/members_only/shb/forms.py", line 8, in <module>
class SHBForm(forms.ModelForm):
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/models.py", line 285, in __new__
opts.help_texts, opts.error_messages)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/models.py", line 212, in fields_for_model
formfield = f.formfield(**kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1970, in formfield
'queryset': self.rel.to._default_manager.using(db),
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/vagrant/members_only/roster/models.py", line 51, in get_queryset
user__groups__name=GROUP_MEMBER
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 679, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 697, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1304, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1332, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1144, in build_filter
lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1030, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1367, in names_to_path
if field.is_relation and not field.related_model:
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/utils/functional.py", line 60, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 110, in related_model
apps.check_models_ready()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
EDIT: SHBForm
class SHBForm(forms.ModelForm):
class Meta:
model = SHB
fields = (
'director', # foreignkey to RosterEntry
...
)
def __init__(self, *args, **kwargs):
super(SHBForm, self).__init__(*args, **kwargs)
self.fields['director'].queryset = RosterEntry.objects.get_all_active_members()
...

Related

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.- django 1.11

After trying to implement Token Authentication using DRF, i get this error raised in my terminal. I have had seen other related relevant questions with solutions but none of them solved my issue.
Below is my wsgi.py
"""
WSGI config for myApp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myApp.settings")
application = get_wsgi_application()
stack trace
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute
django.setup()
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models()
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.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/emmnock/Desktop/peaceAppProject/peaceApp/peace/models.py", line 28, in <module>
Token.objects.get_or_create(user=user)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 464, in get_or_create
return self.get(**lookup), False
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 371, in get
clone = self.filter(*args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 782, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 800, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1261, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1287, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1165, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1045, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1342, in names_to_path
if field.is_relation and not field.related_model:
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/fields/related.py", line 115, in related_model
apps.check_models_ready()
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/apps/registry.py", line 132, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Try editing your wsgi.py like this,
import os
from django.core.wsgi import get_wsgi_application
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = get_wsgi_application()

ProgrammingError when upgrading from Django 1.8 to 1.9

I have project with multiple apps in it. One of the apps has a Contact model and a Supplier model. The Supplier has a OneToOne relation to the Contact model. Everything worked fine in Django 1.8.11. When I attempt to makemigrations or any other command, I get the following error.
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "D:\env\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
utility.execute()
File "D:\env\lib\site-packages\django\core\management\__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\env\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\env\lib\site-packages\django\core\management\base.py", line 398, in execute
self.check()
File "D:\env\lib\site-packages\django\core\management\base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "D:\env\lib\site-packages\django\core\checks\registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\env\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "D:\env\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "D:\env\lib\site-packages\django\utils\functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\lib\site-packages\django\core\urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\env\lib\site-packages\django\utils\functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\lib\site-packages\django\core\urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "D:\mdjango\mdjango\urls.py", line 32, in <module>
url(r'^parts?/', include('parts.urls')),
File "D:\env\lib\site-packages\django\conf\urls\__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "D:\mdjango\parts\urls.py", line 2, in <module>
from parts import views, ajax_views
File "D:\mdjango\parts\views.py", line 9, in <module>
from parts import forms
File "D:\mdjango\parts\forms.py", line 17, in <module>
class PartForm(forms.ModelForm):
File "D:\mdjango\parts\forms.py", line 20, in PartForm
class Meta:
File "D:\mdjango\parts\forms.py", line 26, in Meta
"/contacts/create/?next=/parts/create", "Add Supplier")
File "D:\mdjango\general\widgets.py", line 9, in __init__
super(SelectWithButton, self).__init__(attrs, choices)
File "D:\env\lib\site-packages\django\forms\widgets.py", line 514, in __init__
self.choices = list(choices)
File "D:\env\lib\site-packages\django\db\models\query.py", line 258, in __iter__
self._fetch_all()
File "D:\env\lib\site-packages\django\db\models\query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "D:\env\lib\site-packages\django\db\models\query.py", line 52, in __iter__
results = compiler.execute_sql()
File "D:\env\lib\site-packages\django\db\models\sql\compiler.py", line 848, in execute_sql
cursor.execute(sql, params)
File "D:\env\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "D:\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "D:\env\lib\site-packages\django\db\utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "D:\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "contacts_supplier" does not exist
LINE 1: ...tacts_supplier"."default_contract_target_id" FROM "contacts_...
Basically, I have a URL file in my Parts app that is importing from parts.views, which is standard Django procedure. The parts.views file is importing from parts.forms, also standard Django procedure. The form that is causing issues is this:
class PartForm(forms.ModelForm):
class Meta:
model = Part
fields = ['supplier', 'number', 'name']
widgets = {
'supplier': SelectWithButton(None, Supplier.objects.all(),
"/contacts/create/?next=/parts/create", "Add Supplier")
}
Here's the SelectWithButton class:
from django.forms import Select
from django.template.loader import get_template
class SelectWithButton(Select):
def __init__(self, attrs=None, choices=(), btn_url='', btn_txt=''):
super(SelectWithButton, self).__init__(attrs, choices)
self.btn_url = btn_url
self.btn_txt = btn_txt
def render(self, name, value, attrs=None, choices=()):
context = {'href': self.btn_url, 'text': self.btn_txt,
'select_field': super(SelectWithButton, self).render(name, value, attrs, choices)}
t = get_template("general\selectWithButton.html")
return t.render(context)
The error seems to be that it is trying to get all the objects from Supplier before the migrations have been done. But I'm trying to make the migrations, and I'm getting this error. I did read that Django 1.9 now checks the URL files in the manage.py command, but it seems that I have done nothing out of the ordinary. You can read more here on the 1.9.3 page: https://docs.djangoproject.com/en/1.9/releases/1.9.3/
When I comment out the reference to SelectWithButton, I get a similar error on another form that has an autocomplete_light.MultipleChoiceField on it. What am I doing wrong? It works fine in Django 1.8.11.
Here is the other error and form:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "D:\env\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
utility.execute()
File "D:\env\lib\site-packages\django\core\management\__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\env\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\env\lib\site-packages\django\core\management\base.py", line 398, in execute
self.check()
File "D:\env\lib\site-packages\django\core\management\base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "D:\env\lib\site-packages\django\core\checks\registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\env\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "D:\env\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "D:\env\lib\site-packages\django\utils\functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\lib\site-packages\django\core\urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\env\lib\site-packages\django\utils\functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\lib\site-packages\django\core\urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "D:\mdjango\mdjango\urls.py", line 33, in <module>
url(r'^transactions?/', include('transactions.urls')),
File "D:\env\lib\site-packages\django\conf\urls\__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "D:\mdjango\transactions\urls.py", line 3, in <module>
from views import *
File "D:\mdjango\transactions\views.py", line 3, in <module>
from forms import *
File "D:\mdjango\transactions\forms.py", line 18, in <module>
class InventoryTransactionForm(forms.ModelForm):
File "D:\mdjango\transactions\forms.py", line 32, in InventoryTransactionForm
required=False)
File "D:\env\lib\site-packages\autocomplete_light\fields.py", line 74, in __init__
self.get_choices(autocomplete, registry, widget)})
File "D:\env\lib\site-packages\autocomplete_light\fields.py", line 82, in get_choices
return ((a.choice_value(c), a.choice_label(c)) for c in a.choices)
File "D:\env\lib\site-packages\django\db\models\query.py", line 258, in __iter__
self._fetch_all()
File "D:\env\lib\site-packages\django\db\models\query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "D:\env\lib\site-packages\django\db\models\query.py", line 52, in __iter__
results = compiler.execute_sql()
File "D:\env\lib\site-packages\django\db\models\sql\compiler.py", line 848, in execute_sql
cursor.execute(sql, params)
File "D:\env\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "D:\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "D:\env\lib\site-packages\django\db\utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "D:\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "parts_sns" does not exist
LINE 1: SELECT "parts_sns"."id", "parts_sns"."sn" FROM "parts_sns"
The form:
class InventoryTransactionForm(forms.ModelForm):
parent_sn = autocomplete_light.ModelChoiceField(label="Parent SN", autocomplete='InventoryParentSNAutocomplete',
required=False)
qty_in = forms.FloatField(label="In", required=False)
qty_out = forms.FloatField(label="Out", required=False)
notes = forms.CharField(required=False)
part = autocomplete_light.ModelChoiceField(autocomplete="StandardAutocomplete")
document = autocomplete_light.ModelChoiceField(autocomplete="OpenDocumentAutocomplete", required=False)
# for Qty Out serial numbers
sns = autocomplete_light.MultipleChoiceField(label="SNs", autocomplete='InventoryQtyOutSNsAutocomplete',
required=False)
user = forms.ModelChoiceField(Employee.objects.filter(user__is_active=True))
class Meta:
model = Transaction
fields = ['date', 'usage', 'notes', 'user', 'sns']
Your form is causing the Supplier.objects.all() queryset to be evaluated before the supplier table has been created in the database.
You can get around this by setting the widget in the form's __init__ method.
class PartForm(forms.ModelForm):
class Meta:
model = Part
fields = ['supplier', 'number', 'name']
def __init__(self, *args, **kwargs):
super(PartForm, self).__init__(*args, **kwargs)
self.fields['supplier'].widget = SelectWithButton(
None,
Supplier.objects.all(),
"/contacts/create/?next=/parts/create",
"Add Supplier",
)

OperationalError: no such table: django_content_type when using unittest

I'm trying to launch unittest for my django project and it returns me below error:
ERROR: varys.users.tests.test_all_views (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: varys.users.tests.test_all_views
Traceback (most recent call last):
File "/usr/lib/python2.7/unittest/loader.py", line 254, in _find_tests
module = self._get_module_from_name(name)
File "/usr/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name
__import__(name)
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/users/tests/__init__.py", line 1, in <module>
from .test_all_views import *
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/users/tests/test_all_views.py", line 12, in <module>
from ...urls import urlpatterns
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/urls.py", line 18, in <module>
url(r'^survey/', include('varys.surveys.urls')),
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 26, in include
urlconf_module = import_module(urlconf_module)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/surveys/urls.py", line 13, in <module>
from .userrankingreview.views import UserRankingReviewView
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/surveys/userrankingreview/views.py", line 6, in <module>
from .forms import UserRankingReviewFormset
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/surveys/userrankingreview/forms.py", line 63, in <module>
formfield_callback=formfield_callback
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/forms/models.py", line 981, in inlineformset_factory
FormSet = modelformset_factory(model, **kwargs)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/forms/models.py", line 813, in modelformset_factory
labels=labels, help_texts=help_texts, error_messages=error_messages)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/forms/models.py", line 528, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/forms/models.py", line 282, in __new__
opts.help_texts, opts.error_messages)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/forms/models.py", line 205, in fields_for_model
formfield = formfield_callback(f, **kwargs)
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/surveys/userrankingreview/forms.py", line 54, in formfield_callback
return field.formfield()
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1263, in formfield
'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to),
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/manager.py", line 226, in using
return self.get_queryset().using(*args, **kwargs)
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/surveys/models.py", line 199, in get_query_set
qs = qs.filter(**self.model.subclasses_lookup())
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/polymodels/models.py", line 59, in subclasses_lookup
query_name=query_name
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/polymodels/models.py", line 50, in content_type_lookup
value = [ct.pk for ct in get_content_types(models).values()]
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/polymodels/utils.py", line 26, in get_content_types
return manager.get_for_models(*models, for_concrete_models=False)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 79, in get_for_models
for ct in cts:
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/query.py", line 96, in __iter__
self._fetch_all()
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 713, in results_iter
for rows in self.execute_sql(MULTI):
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 451, in execute
return Database.Cursor.execute(self, query, params)
OperationalError: no such table: django_content_type
Yesterday all tests worked well. After checking I noticed that issue is in below code
# forms.py
UserRankingReviewFormset = inlineformset_factory(
UserRankingReviewRequest,
UserRankingReview,
formset=UserRankingInlineFormSet,
extra=0,
can_delete=False,
formfield_callback=formfield_callback
)
where parent_model UserRankingReviewRequest is Proxy model and UserRankingReview model has foreignkey 'request' to UserRankingReviewRequest.
When I set flag Proxy = False for this model then tests work well, but I need this model as Proxy only
any ideas how I can prevent this?
Proxy = True
means that there is no actual database table created for the model. So, when you try to reference the model with a ForeignKey, things break (since the ForeignKey has no db table to point to).
If what you are trying to achieve is to have a "Generic abstract" type object with concrete sub-type and want a foreign-key to any of the sub-types I would recommend checking out https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#generic-relations (with a custom limit_choices_to on the ForeignKey to ContentType https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to)
You might also be interested in Django Polymorphic (https://django-polymorphic.readthedocs.org/en/latest/) which does all that and more.
If this is happening in tests as it does for me,
maybe this link
can help, in short the answer is:
Ok, I found a way around the problem, in case anyone ever has the same
problem. If you specify TEST_DATABASE_NAME in your settings, it will
force sqllite to use a file database instead of in-memory database,
and then the problem goes.

Programmatically set the model on a class based view in Django 1.3

I'm trying to implement a more generic version of the Django class based detail view, which can operate on different models when required. The idea was to set the model using a parameter in the URL, like so:
url(r'^product/view/(?P<bought_in_control_panel_id>\d+)/(?P<item_uuid>'+uuid_re+'/)',
GenericModelDetailView().as_view(pk_url_kwarg='item_uuid',
template_name='suppliers/products/view_product.html')
, name='view_product'),
This is the class that i'm using, but django is complaining about the class not having an object attribute.
class GenericModelDetailView(DetailView):
def __init__(self, *args, **kwargs):
self.model = get_model_for_bought_in_control_panel(super(GenericModelDetailView, self).get_context_data(**kwargs)['bought_in_control_panel_id'])
super(GenericModelDetailView, self).__init__(**kwargs)
Stacktrace:
File "django/core/handlers/base.py", line 89, in get_response
response = middleware_method(request)
File "django/middleware/common.py", line 67, in process_request
if (not _is_valid_path(request.path_info, urlconf) and
File "django/middleware/common.py", line 154, in _is_valid_path
urlresolvers.resolve(path, urlconf)
File "django/core/urlresolvers.py", line 342, in resolve
return get_resolver(urlconf).resolve(path)
File "django/core/urlresolvers.py", line 252, in resolve
sub_match = pattern.resolve(new_path)
File "django/core/urlresolvers.py", line 250, in resolve
for pattern in self.url_patterns:
File "django/core/urlresolvers.py", line 279, in _get_url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "django/core/urlresolvers.py", line 274, in _get_urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/jsoft/jmsdirectory/srv/jmsdirectory/../jmsdirectory/suppliers/urls.py", line 29, in <module>
GenericModelDetailView().as_view(pk_url_kwarg='item_uuid',
File "jmsdirectory/suppliers/products.py", line 79, in __init__
self.model = get_model_for_bought_in_control_panel(super(GenericModelDetailView, self).get_context_data(**kwargs)['bought_in_control_panel_id'])
File "django/views/generic/detail.py", line 90, in get_context_data
context_object_name = self.get_context_object_name(self.object)

Django Model SyncDB fail on the choices attribute due to a DB error

Here is a little error I get when trying to use syncdb on my django project.
Error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 219, in execute
self.validate()
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 146, in get_app_errors
self._populate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/opt/admin-site/adminsite/cfadmin/models.py", line 111, in <module>
class RequestLog(models.Model):
File "/opt/admin-site/adminsite/cfadmin/models.py", line 117, in RequestLog
profile = models.PositiveIntegerField(null=True,blank=True, choices=get_profiles()) # It cannot be a foreign key this is not on the same DB
File "/opt/admin-site/adminsite/cfadmin/models.py", line 107, in get_profiles
cache.set('profiles_choices', profiles_choices, 3600)
File "/usr/local/lib/python2.6/dist-packages/django/core/cache/backends/locmem.py", line 83, in set
self._set(key, pickle.dumps(value), timeout)
File "/usr/lib/python2.6/copy_reg.py", line 84, in _reduce_ex
dict = getstate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 61, in __getstate__
len(self)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 81, in __len__
self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 947, in iterator
for row in self.query.get_compiler(self.db).results_iter():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 672, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 727, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute
return self.cursor.execute(query, args)
django.db.utils.DatabaseError: relation "cfadmin_profile" does not exist
LINE 1: ...dmin_profile"."id", "cfadmin_profile"."name" FROM "cfadmin_p...
The models:
class Profile(models.Model):
name = models.CharField(max_length=256)
categories = models.ManyToManyField(Category)
def __unicode__(self):
return self.name
class Meta():
ordering = ["name"]
def get_profiles():
profiles_choices = cache.get('profiles_choices')
if profiles_choices == None:
try:
profiles_choices = Profile.objects.values_list('id','name')
cache.set('profiles_choices', profiles_choices, 3600)
except:
logging.info("Failed to retrieve the profile choices.")
pass
return profiles_choices
class Log(models.Model):
domain = models.CharField(max_length=512)
profile = models.PositiveIntegerField(null=True,blank=True, choices=get_profiles()) # this is where I get the error on Syncdb
def __unicode__(self):
return self.domain
class Meta():
ordering = ["domain"]
So if I am syncing a new project I will get the error that I mentioned earlier.
If I remove the call to my function get_profiles() in the model choices, it will synchronize with no error.
But I don't understand why I'm still getting the error even do I put a try catch within the function.
So in case of an error I would expect that it continues but instead it's completely aborting the syncdb.
Is there anyway to achieve what I'm trying to without removing the function and the put it back?
Thank you!
From the django doc " ... if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever."
So you are probably better of changing your profile field in the Log model:
profile = models.ForeignKey(Profile, null=True,blank=True)
This is not the way to get choices for a model. Even if you fix your circular dependency problem, you will still have the issue that the get_choices() function will be called when the server process starts, and won't change in the meantime. Unlike default, I don't believe choices can be a callable.