I would like to create a custom queryset for my User model.
However, I cannot simply use objects = UserQuerySet.as_manager() since the standard Django User model already has a custom UserManager.
My code is simply :
class UserQuerySet(MyBaseQuerySet):
def opted_out_method(self):
return
class User(AbstractUser):
objects = UserManager.from_queryset(UserQuerySet)()
# etc...
This code works, except when I do this:
$manage.py makemigrations --dry-run
File "./manage.py", line 49, in <module>
execute_from_command_line(sys.argv)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 164, in handle
changes = autodetector.changes(
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/autodetector.py", line 43, in changes
changes = self._detect_changes(convert_apps, graph)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/autodetector.py", line 129, in _detect_changes
self.new_apps = self.to_state.apps
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 210, in apps
return StateApps(self.real_apps, self.models)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 273, in __init__
self.render_multiple([*models.values(), *self.real_models])
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 308, in render_multiple
model.render(self)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 577, in render
body.update(self.construct_managers())
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 536, in construct_managers
as_manager, manager_path, qs_path, args, kwargs = manager.deconstruct()
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 61, in deconstruct
raise ValueError(
The exception raised is "Could not find manager. Please note that you need to inherit from managers you dynamically generated with 'from_queryset()", which is what I'm doing.
Has anyone run into this before?
I'm currently using Django 2.2, not sure if this is fixed in 3+.
The solution is to create a custom manager that derives from UserManager.
from django.contrib.auth.models import UserManager
class MyCustomUserManager(UserManager):
def bob_filter(self):
return super().get_queryset().filter(first_name__icontains="bob")
# etc...
class User(AbstractUser):
objects = managers.CustomUserManager()
# etc...
Related
When I'm trying to make migrations of my models in Django, I keep getting the same error, even after I've commented out all the changes:
(.venv) C:\Users\jezdo\venv\chat\chat_proj>python manage.py makemigrations chat
Migrations for 'chat':
chat\migrations\0002_alter_customusergroup_custom_group_name_and_more.py
- Alter field custom_group_name on customusergroup
- Alter field users on customusergroup
Traceback (most recent call last):
File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 22, in <module>
main()
File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
utility.execute()
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 448, in execute
output = self.handle(*args, **options)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 239, in handle
self.write_migration_files(changes)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 278, in write_migration_files
migration_string = writer.as_string()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 141, in as_string
operation_string, operation_imports = OperationWriter(operation).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 99, in serialize
_write(arg_name, arg_value)
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 63, in _write
arg_string, arg_imports = MigrationWriter.serialize(_arg_value)
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 282, in serialize
return serializer_factory(value).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 221, in serialize
return self.serialize_deconstructed(path, args, kwargs)
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 99, in serialize_deconstructed
arg_string, arg_imports = serializer_factory(arg).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize
item_string, item_imports = serializer_factory(item).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize
item_string, item_imports = serializer_factory(item).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 386, in serializer_factory
raise ValueError(
ValueError: Cannot serialize: <User: jezdo>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/4.1/topics/migrations/#migration-serializing
my model in models.py:
class CustomUserGroup(models.Model):
custom_group_name = models.CharField(max_length=50, unique=True)
users= MultiSelectField(max_length=100,choices=users_list,unique=False)
class Meta:
verbose_name_plural = 'Custom Groups'
ordering = ['custom_group_name']
def __unicode__(self):
return self.custom_group_name
I wanted to create another model similar to CustomUserGroup byt with a different "users" field:
class CustomUserGroup2(models.Model):
custom_group_name = models.CharField(max_length=50, unique=True)
users= models.ManyToManyField(User)
class Meta:
verbose_name_plural = 'Custom Groups'
ordering = ['custom_group_name']
def __unicode__(self):
return self.custom_group_name
but couldn't makemigrations due to the described error. Now I cannot make any migrations whatsoever, even after having deleted the CustomUserGroup2 class.
I'm using Python 3.10.4 and Django 4.1.6.
I want to use Locust as a library in Django's Unittest framework, because I want Django (3.1.2) to create a temporary database for me to do the testing. However, I receive the following error:
Traceback (most recent call last):
File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_test_manage.py", line 104, in handle
failures = TestRunner(test_labels, **options)
File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_test_runner.py", line 254, in run_tests
return DjangoTeamcityTestRunner(**options).run_tests(test_labels,
File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_test_runner.py", line 156, in run_tests
return super(DjangoTeamcityTestRunner, self).run_tests(test_labels, extra_tests, **kwargs)
File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/test/runner.py", line 695, in run_tests
old_config = self.setup_databases(aliases=databases)
File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/test/runner.py", line 614, in setup_databases
return _setup_databases(
File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/test/utils.py", line 170, in setup_databases
connection.creation.create_test_db(
File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/db/backends/base/creation.py", line 57, in create_test_db
self.connection.close()
File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 285, in close
self.validate_thread_sharing()
File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 552, in validate_thread_sharing
raise DatabaseError(
django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 4487204352 and this is thread id 4528855696.
I don't seem to be able to even import Locust, for example, the following test_locust.py, which does nothing, can already reproduce the error:
from django.test import TransactionTestCase
from locust.env import Environment
class MyTestCase(TransactionTestCase):
def test_cart(self):
pass
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 running tests with nose and would like to take advantage of the --failed flag. But as soon as I add it I get errors like these for user related models:
./manage.py test # works
./manage.py test --failed # fails
CommandError: One or more models did not validate:
vod.video: 'user' has a relation with model accounts.CustomUser, which has either not been installed or is abstract.
Packages:
Django==1.6.7
django-nose==1.3
nose==1.3.4
What am I doing wrong?
Update: I don't see the issue on my master branch. In the new branch I'm started to use the TenantTestCase class from django-tenant-schemas. May be the cause of the problem.
The traceback I get:
./manage.py test --failed --traceback
nosetests --failed --verbosity=1
Creating test database for alias 'default'...
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/core/management/commands/test.py", line 50, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/core/management/commands/test.py", line 71, in execute
super(Command, self).execute(*args, **options)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/home/dev/envs/py26/lib/python2.6/site-packages/south/management/commands/test.py", line 8, in handle
super(Command, self).handle(*args, **kwargs)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/core/management/commands/test.py", line 88, in handle
failures = test_runner.run_tests(test_labels)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django_nose/runner.py", line 218, in run_tests
result = self.run_suite(nose_argv)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django_nose/runner.py", line 165, in run_suite
addplugins=plugins_to_add)
File "/home/dev/envs/py26/lib/python2.6/site-packages/nose/core.py", line 121, in __init__
**extra_args)
File "/usr/lib/python2.6/unittest.py", line 817, in __init__
self.runTests()
File "/home/dev/envs/py26/lib/python2.6/site-packages/nose/core.py", line 207, in runTests
result = self.testRunner.run(self.test)
File "/home/dev/envs/py26/lib/python2.6/site-packages/nose/core.py", line 50, in run
wrapper = self.config.plugins.prepareTest(test)
File "/home/dev/envs/py26/lib/python2.6/site-packages/nose/plugins/manager.py", line 99, in __call__
return self.call(*arg, **kw)
File "/home/dev/envs/py26/lib/python2.6/site-packages/nose/plugins/manager.py", line 167, in simple
result = meth(*arg, **kw)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django_nose/plugin.py", line 76, in prepareTest
self.old_names = self.runner.setup_databases()
File "/home/dev/envs/py26/lib/python2.6/site-packages/django_nose/runner.py", line 401, in setup_databases
return super(NoseTestSuiteRunner, self).setup_databases()
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/test/runner.py", line 107, in setup_databases
return setup_databases(self.verbosity, self.interactive, **kwargs)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/test/runner.py", line 279, in setup_databases
verbosity, autoclobber=not interactive)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/db/backends/creation.py", line 339, in create_test_db
load_initial_data=False)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/core/management/__init__.py", line 159, in call_command
return klass.execute(*args, **defaults)
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/core/management/base.py", line 284, in execute
self.validate()
File "/home/dev/envs/py26/lib/python2.6/site-packages/django/core/management/base.py", line 314, in validate
raise CommandError("One or more models did not validate:\n%s" % error_text)
django.core.management.base.CommandError: One or more models did not validate:
vod.video: 'user' has a relation with model accounts.CustomUser, which has either not been installed or is abstract.
I think it has to do with the custom user model. Check this out https://github.com/bernardopires/django-tenant-schemas/issues/237
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.