After upgrading django from 1.10.6 to 1.11 while runserver I am getting following exception.
models.Q is inherited from tree.Node and there is no significant change around this in both the versions that could break usage of Q.
class LimitTagAssociations():
def __init__(self, criteria):
self.criteria = criteria
def add_to_query(self, query, aliases):
query.add_q(models.Q(id__in=[1, 2, 3]))
query.distinct = True
class Cat(models.Model):
new_and_now_reco_base = fields.IntegerRangeField(min_value=500, max_value=10000, default=1000)
auto_taggroups = models.ManyToManyField(TagGroup, null=True, blank=True, limit_choices_to=LimitTagAssociations('1'))
manual_taggroups = models.ManyToManyField(TagGroup, null=True, blank=True, limit_choices_to=LimitTagAssociations('2'))
abs_url = models.CharField(max_length=255, blank=True, null=True)
primary_filter_select = models.ManyToManyField(TagGroup, null=True, blank=True, limit_choices_to=LimitTagAssociations('3'))
class CatAdminForm(forms.ModelForm):
class Meta:
model = Cat
exclude = ()
Traceback (most recent call last):
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception
six.reraise(*_exception)
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/apps/registry.py", line 116, in populate
app_config.ready()
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib/python2.7/importlib/__init__.py", line 38, in import_module
__import__(name)
File "/srv/webapps/myproj.com/myproj/product/admin.py", line 6, in <module>
from product.forms import ProdFilterForm, BrandAdminForm
File "/srv/webapps/myproj.com/myproj/product/forms.py", line 124, in <module>
class CatAdminForm(forms.ModelForm):
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/forms/models.py", line 252, in __new__
opts.field_classes)
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/forms/models.py", line 177, in fields_for_model
formfield.queryset = formfield.queryset.complex_filter(limit_choices_to)
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/db/models/query.py", line 814, in complex_filter
clone.query.add_q(filter_obj)
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1260, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/srv/webapps/myproj.com/virtualenvs/myproj/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1270, in _add_q
connector = q_object.connector
AttributeError: LimitTagAssociations instance has no attribute 'connector'
Related
So I'm trying to integrate a model with mongoDB usng djongo driver, and when I tried to insert a record from within models.py it is giving me this error.I'm a newbie and trying to get my hands on django. Please have a look and explain that where and why I'm wrong/ Thank you.
AppRegistryNotReady("Models aren't loaded yet.")
here are my code files.
models.py
from djongo import models
class Iname(models.Model):
item_name = models.TextField()
class Meta:
abstract = True
class Iquantity(models.Model):
item_quantity = models.FloatField()
class Meta:
abstract = True
class Iprice(models.Model):
item_price = models.FloatField()
class Meta:
abstract = True
class Order(models.Model):
email = models.EmailField(primary_key = True, name = "email")
name = models.CharField(max_length=30, help_text="Enter Customer Name", name = "name")
address = models.TextField(help_text="Enter customer's Address", name = "address")
item_names = models.ArrayField(model_container = Iname)
item_quantities = models.ArrayField(model_container = Iquantity)
item_prices = models.ArrayField(model_container = Iprice)
objects = models.DjongoManager()
o = Order()
o.email = "jayesh#gmail.com"
o.name = "dhsdb"
o.address = "agdkhdvf"
o.item_names = ['chocolate', 'pencil']
o.item_quantities = [5, 10]
o.item_prices = [10, 3]
o.save()
serializers.py
from .models import Order, Iname, Iprice, Iquantity
from rest_framework import serializers
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Iname
class QuantitySerializer(serializers.ModelSerializer):
class Meta:
model = Iquantity
class PriceSerializer(serializers.ModelSerializer):
class Meta:
model = Iprice
class OrderSerializer(serializers.ModelSerializer):
item_names = ItemSerializer()
item_quantities = QuantitySerializer()
item_prices = PriceSerializer()
class Meta:
model = Order
fields = "__all__"
views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import OrderSerializer
from .models import Order
#api_view(['GET',])
def get_orders(request):
orders = Order.objects.all()
serializer = OrderSerializer(instance = orders, many = True)
print(serializer.data)
return Response(data = serializer.data)
And yes here is my traceback
C:\Users\ACER\Desktop\invoice\base\models.py changed, reloading.
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "c:\users\acer\anaconda3\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "c:\users\acer\anaconda3\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run
autoreload.raise_last_exception()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
raise _exception[1]
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\core\management\__init__.py", line 398, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\apps\registry.py", line 116, in populate
app_config.import_models()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\apps\config.py", line 304, in import_models
self.models_module = import_module(models_module_name)
File "c:\users\acer\anaconda3\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 "C:\Users\ACER\Desktop\invoice\base\models.py", line 64, in <module>
o.save()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\base.py", line 857, in save_base
updated = self._save_table(
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\base.py", line 970, in _save_table
updated = self._do_update(
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\base.py", line 1034, in _do_update
return filtered._update(values) > 0
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\query.py", line 885, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\sql\compiler.py", line 1783, in execute_sql
cursor = super().execute_sql(result_type)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\sql\compiler.py", line 1348, in execute_sql
sql, params = self.as_sql()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\sql\compiler.py", line 1749, in as_sql
val = field.get_db_prep_save(val, connection=self.connection)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\djongo\models\fields.py", line 229, in get_db_prep_save
processed_value = self._save_value_thru_fields('get_db_prep_save',
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\djongo\models\fields.py", line 344, in _save_value_thru_fields
post_dict = super()._save_value_thru_fields(func_name,
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\djongo\models\fields.py", line 155, in _save_value_thru_fields
for field in self.model_container._meta.get_fields():
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\options.py", line 849, in get_fields
return self._get_fields(
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\options.py", line 928, in _get_fields
all_fields = self._relation_tree
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\utils\functional.py", line 49, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\options.py", line 822, in _relation_tree
return self._populate_directed_relation_graph()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\options.py", line 789, in _populate_directed_relation_graph
all_models = self.apps.get_models(include_auto_created=True)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\apps\registry.py", line 181, in get_models
self.check_models_ready()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\apps\registry.py", line 143, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
list of dependencies i'm using
asgiref==3.5.2
backports.zoneinfo==0.2.1
Django==4.0.5
djangorestframework==3.13.1
djongo==1.3.6
pymongo==3.12.3
pytz==2022.1
sqlparse==0.2.4
tzdata==2022.1
I'm using django 1.8. When I use a datetime field, I get an error saying that the field is unknown.
I checked many times that the name is spelled right.
Any ideas what's going on here?
class MyTable(models.Model):
origin = models.PositiveIntegerField(null=True, blank=True)
last_modified = models.DateTimeField(auto_now=True)
class MyTableForm(ModelForm):
class Meta:
model = MyTable
fields = ['origin', 'last_modified']
Traceback (most recent call last):
File "manage.py", line 19, in <module>
execute_from_command_line(sys.argv)
File "/home/user/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/user/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/home/user/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/user/venv/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/home/user/venv/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 22, in ready
self.module.autodiscover()
File "/home/user/venv/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/home/user/venv/lib/python2.7/site-packages/django/utils/module_loading.py", line 74, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/user/src/biosys/myapp/myapp/admin.py", line 6, in <module>
from forms import *
File "/home/user/src/biosys/myapp/myapp/forms.py", line 46, in <module>
class InterpForm(ModelForm):
File "/home/user/venv/lib/python2.7/site-packages/django/forms/models.py", line 295, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (last_modified) specified for MyTable
I am working with a Django application with Postgres Database.
My models are as follows:
from django.db import models
from django.contrib.auth.models import User as UserModel
from dynamicforms.mangers import TextQuestionManager, MCQManager, IntegerQuestionManager
from django.db.models.fields.related import OneToOneRel
from django.contrib.postgres import fields as postgres_fields
Qtypes = [(1, "Multiple Choice Question"), (2, "Text Question"), (3, "integer Type Question")]
COMPS = [(True, 'Yes'), (False, 'No')]
SECTIONS = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
class QuestionModel(models.Model):
qtype = models.IntegerField(null=False, choices=Qtypes)
text = models.TextField(max_length=500, null=False, blank=False)
description = models.TextField(max_length=1000, null=True, blank=True)
help_text = models.CharField(max_length=300, null=True, blank=True)
is_compulsory = models.BooleanField(default=True, null=False, choices=COMPS)
def __str__(self):
return self.text
class TextQuestionModel(QuestionModel):
nextQ = postgres_fields.ArrayField(models.IntegerField(blank=True, null=True), null=True, blank=True)
objects = TextQuestionManager()
class MCQModel(QuestionModel):
objects = MCQManager()
class Meta:
proxy = True
class IntegerQuestionModel(QuestionModel):
nextQ = postgres_fields.ArrayField(models.IntegerField(blank=True, null=True), null=True, blank=True)
objects = IntegerQuestionManager()
I made few changes to my schema.So i have to reset my DB.I reseted my DB and migrations and when im trying to run
python manage.py makemigrations
I am getting this error.I tried changing db and changing user and everything.I dont understand what made this error.
Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace instance at 0x7fa990057998>
Traceback (most recent call last):
File "/opt/pycharm/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 553, in __call__
return self.original_func(*self.args, **self.kwargs)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run
autoreload.raise_last_exception()
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/phani/Projects/Freewill/dynamicforms/admin.py", line 3, in <module>
from dynamicforms.forms import MCQFormAdmin, TextFormAdmin, IntegerFormAdmin
File "/home/phani/Projects/Freewill/dynamicforms/forms.py", line 6, in <module>
QS = [(i.id, i.text) for i in QuestionModel.objects.all()]
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 256, in __iter__
self._fetch_all()
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql()
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "dynamicforms_questionmodel" does not exist
LINE 1: ..."dynamicforms_questionmodel"."is_compulsory" FROM "dynamicfo...
^
Can someone help me with this?Thanks in advance
You reseted all files in project. But migrations history saved in django_migrations tables . You also must clean this table.
Are you deleted 'migrations' folder in your app?
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",
)
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()
...