Django version 1.11, sqlite3 version 3.11.
I'm using WAL mode and a long timeout:
from django.apps import AppConfig
from django.db.backends.signals import connection_created
class SQLite3Config(AppConfig):
name = 'sqlite3_config'
def ready(self):
connection_created.connect(configure_sqlite)
# noinspection PyUnusedLocal
def configure_sqlite(sender, connection, **_):
if connection.vendor == 'sqlite':
cursor = connection.cursor()
cursor.execute('PRAGMA journal_mode=WAL;')
cursor.execute('PRAGMA busy_timeout=5000;')
I want to retain sqlite3 and not move to mysql or postgres because the application is small and is installed by users on multiple servers.
I believe WAL should allow "concurrent" writes by serializing them. The "Database is locked" problem was observed when small bursts (half a dozen or so) were received together.
I can reproduce the problem in the shell with threads. The django model method simply sets a flag and saves the model:
def activate(self):
self.activate = True
self.save()
When I use threads I find it fails if I launch a few threads that attempt it at the same time. There is no wait so the timeout is not involved. The error occurs before the 5 second busy timeout has elapsed (in less than two seconds):
In [2]: [NGThread(notifier_group.id).start() for notifier_group in NotifierGroup.objects.all()[:2]]
Out[2]: [None, None]
In [3]: [NGThread(notifier_group.id).start() for notifier_group in NotifierGroup.objects.all()[:3]]
Out[3]: [None, None, None]
In [4]: [NGThread(notifier_group.id).start() for notifier_group in NotifierGroup.objects.all()[:4]]
Out[4]: [None, None, None, None]
In [5]: Exception in thread Thread-97:
Traceback (most recent call last):
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: database is locked
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/home/paul/wk/cliosoft/sosadmin/scratch.py", line 41, in run
toggle_active(notifier_group)
File "/home/paul/wk/cliosoft/sosadmin/scratch.py", line 30, in toggle_active
model.activate()
File "/home/paul/wk/cliosoft/sosadmin/notifications/models/notifier_group.py", line 67, in activate
self.save()
File "/home/paul/wk/cliosoft/sosadmin/notifications/models/notifier_group.py", line 33, in save
self.verify()
File "/home/paul/wk/cliosoft/sosadmin/notifications/models/notifier_group.py", line 46, in verify
self.create_notifier(base_spec, model_set, group_event_condition)
File "/home/paul/wk/cliosoft/sosadmin/notifications/models/notifier_group.py", line 57, in create_notifier
notifier.users = self.users.all()
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 534, in __set__
manager.set(value)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 1004, in set
self.add(*new_objs)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 931, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 1100, in _add_is
for obj_id in new_ids
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/query.py", line 442, in bulk_create
ids = self._batched_insert(objs_without_pk, fields, batch_size)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/query.py", line 1083, in _batched_insert
self._insert(item, fields=fields, using=self.db)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/query.py", line 1060, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql
cursor.execute(sql, params)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: database is locked
Exception in thread Thread-98:
Traceback (most recent call last):
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: database is locked
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/home/paul/wk/cliosoft/sosadmin/scratch.py", line 41, in run
toggle_active(notifier_group)
File "/home/paul/wk/cliosoft/sosadmin/scratch.py", line 28, in toggle_active
model.deactivate()
File "/home/paul/wk/cliosoft/sosadmin/notifications/models/notifier_group.py", line 72, in deactivate
self.save()
File "/home/paul/wk/cliosoft/sosadmin/notifications/models/notifier_group.py", line 33, in save
self.verify()
File "/home/paul/wk/cliosoft/sosadmin/notifications/models/notifier_group.py", line 46, in verify
self.create_notifier(base_spec, model_set, group_event_condition)
File "/home/paul/wk/cliosoft/sosadmin/notifications/models/notifier_group.py", line 57, in create_notifier
notifier.users = self.users.all()
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 534, in __set__
manager.set(value)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 1004, in set
self.add(*new_objs)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 931, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 1100, in _add_is
for obj_id in new_ids
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/query.py", line 442, in bulk_create
ids = self._batched_insert(objs_without_pk, fields, batch_size)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/query.py", line 1083, in _batched_insert
self._insert(item, fields=fields, using=self.db)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/query.py", line 1060, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql
cursor.execute(sql, params)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/paul/.virtualenvs/sosadmin/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: database is locked
I can't see anything in the release notes but I've upgraded to Django 2.0 and this problem has now disappeared. With the WAL set up in sqlite3 its all working very well now.
As the system has scaled, this error has re-occurred. I'm required to use sqlite3 for reasons outside the scope of this problem.
The timeout option in Django seems to be ignored. I tried implementing it myself at the db cursor level with a wrapper around sqlite and had the same problem (at that level you can't back out far enough to abandon the transaction and try a new connection).
I'd have liked a context manager e.g. with db_locked_retries():... but it is not possible to iterate within the with context so I created a db_retry function thus:
import time
import logging
import random
from django.conf import settings
import django.db
logger = logging.getLogger('django.db.backends')
def db_retry(fn, timeout=None):
"""Call fn with no arguments. If OperationalError exception, make retries until timeout has passed"""
timeout = timeout or settings.DATABASES['default'].get('OPTIONS', dict()).get('timeout', 5)
now = time.time()
give_up_time = now + timeout
retries = 0
while now < give_up_time:
now = time.time()
try:
result = fn()
if retries:
logger.warning(f'db_retry: Succeeded after {retries} retries')
return result
except django.db.OperationalError as exception:
msg = str(exception)
if 'locked' in msg: # pragma: no cover
retries += 1
wait_time = random.uniform(1, timeout / 10)
logger.warning(f'db_retry: {msg}: Retrying after {wait_time} seconds')
django.db.close_old_connections()
time.sleep(wait_time)
else: # pragma: no cover
logger.exception(f'db_retry: {msg}: Giving up')
raise
As it is very easy to define the function to pass to this function within the model methods etc. this addresses the problem and successfully uses the timeout to retry the access. This is currently handling some hundreds of concurrent uses and retries once every thirty minutes or so in my particular use case.
I've only needed to 'wrap' model code that potentially makes several writes so far.
Related
I have a problem with my django server time, it is 2 hours late.
I tried to find a solution but whatever i found (as How to change my django server time, or Django documentation) is not what I think I need.
Right now my computer's time is 23:14:37
When i write in bash date +%H:%M:%S I will get:
(python_env) bash-3.2$ date +%H:%M:%S
23:17:03
So I don't think this is my console problem.
But when I am running my server here is what I get:
(python_env) bash-3.2$ python3 manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
April 04, 2020 - 21:18:47
Django version 2.2.4, using settings 'myVote365.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
The time is now 2 hours late.
I have red that it could be because of wrong timezone, but I have my code similar to How to change my django server time
LANGUAGE_CODE = 'pl'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
What's more it worked perfectly fine just before I change my os to Windows, and to OS X again
Edit:
I changed USE_TZ to False, ran and closed the server, and again to True.
And now although I still have a server 2 hour late. But from error:
Internal Server Error: /panel/
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 189, in _get_session
return self._session_cache
AttributeError: 'SessionStore' object has no attribute '_session_cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_session
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/icookiez/Documents/praca/dla taty/myVote365/myVote365/audytor/views.py", line 26, in panel
if 'auditor' in request.session and request.session['auditor']['logged'] is True:
File "/usr/local/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 51, in __contains__
return key in self._session
File "/usr/local/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 194, in _get_session
self._session_cache = self.load()
File "/usr/local/lib/python3.7/site-packages/django/contrib/sessions/backends/db.py", line 43, in load
s = self._get_session_from_db()
File "/usr/local/lib/python3.7/site-packages/django/contrib/sessions/backends/db.py", line 34, in _get_session_from_db
expire_date__gt=timezone.now()
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 402, in get
num = len(clone)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 256, in __len__
self._fetch_all()
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 55, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_session
I got a working site.
First step
I changed USE_TZ to False, ran and closed the server, and again to True. This allowed my side to load, but still had the wrong time.
Second step
I changed TIME_ZONE not to ‘PL’ as #jatrp5 suggested, but to 'Europe/Warsaw' as I read on this question. Using the zone name form Wikipedia. And now I have time I was wishing for.
To match your bash time you should change the time zone to TIME_ZONE = 'PL'. The universal time zone (UTC) is two hours behind the Polish.
(Using the library django-tenants for tenant separated multi-tenancy) For PostGis support the docs say to add ORIGINAL_BACKEND = "django.contrib.gis.db.backends.postgis". I have this, however, when I go to create a new tenant I get the following error:
Traceback (most recent call last):
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\celery\app\trace.py", line 382, in trace_task
R = retval = fun(*args, **kwargs)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\celery\app\trace.py", line 641, in __protected_call__
return self.run(*args, **kwargs)
File "C:\Users\Cole\Documents\GitHub\Elevate-RA-Django-App\returns_app\apps\tenant_stores\tasks.py", line 28, in create_tenant_task
tenant.save()
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django_tenants\models.py", line 93, in save
self.create_schema(check_if_exists=True, verbosity=verbosity)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django_tenants\models.py", line 143, in create_schema
verbosity=verbosity)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\__init__.py", line 141, in call_command
return command.execute(*args, **defaults)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\base.py", line 335, in execute
output = self.handle(*args, **options)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django_tenants\management\commands\migrate_schemas.py", line 63, in handle
executor.run_migrations(tenants=tenants)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django_tenants\migration_executors\standard.py", line 15, in run_migrations
run_migrations(self.args, self.options, self.codename, schema_name, idx=idx, count=len(tenants))
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django_tenants\migration_executors\base.py", line 34, in run_migrations
MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\base.py", line 335, in execute
output = self.handle(*args, **options)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 77, in handle
connection.prepare_database()
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\contrib\gis\db\backends\postgis\base.py", line 26, in prepare_database
cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis")
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\db\backends\utils.py", line 83, in _execute
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "spatial_ref_sys" does not exist
The spatial_ref_sys table exists within my public schema. The django.contrib.gis app is in my shared apps.
Any ideas?
The issue seems to be cause by the default PostGis backend, specifically the call to prepare the database for migration, by explicitly setting the search path prior to calling CREATE EXTENSION IF NOT EXISTS postgis I was able to migrate/create a schema by creating a custom DB backend that overrides this behaviour:
from django.contrib.gis.db.backends.postgis.base import (
DatabaseWrapper as OriginalPostGisDatabaseWrapper,
)
from django_tenants.utils import get_public_schema_name
class DatabaseWrapper(OriginalPostGisDatabaseWrapper):
"""
This database wrapper explicitly sets the search path when preparing the database, as
multi-schema environments (like with Django-tenants) can cause issues with the PostGis
backend.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.PUBLIC_SCHEMA_NAME = get_public_schema_name()
def prepare_database(self):
# Check that postgis extension is installed.
with self.cursor() as cursor:
cursor.execute('SET search_path = %s', params=[self.PUBLIC_SCHEMA_NAME])
cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis")
Then, set your ORIGINAL_BACKEND setting to the location of the above DB backend instead of the standard PostGis backend.
I'm running into a strange issue when resetting my database. A multiple choice field in a form is throwing exception
Unhandled exception in thread started by .wrapper at 0x7f59df160510>
Traceback (most recent call last):
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: app1_semester
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
......
File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/urls.py", line 3, in
from . import views
File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/views.py", line 10, in
from . import models, forms
File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/forms.py", line 11, in
class AddAssignmentForm(forms.Form):
File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/forms.py", line 14, in AddAssignmentForm
queryset=models.AssignmentType.get_assignment_types(),
File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/models.py", line 180, in get_assignment_types
return AssignmentType.objects.filter(semester=Semester.get_current_semester())
File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/models.py", line 157, in get_current_semester
return semester.first() if semester else None
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 260, in __bool__
self._fetch_all()
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql()
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: app1_semester
If I comment below piece of code in forms.py, everything is working fine.
class AddAssignmentForm(forms.Form):
assignments = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(),queryset=models.AssignmentType.get_assignment_types(),required=False)
The method get_assignment_types() is a static method returning some list of values
models.py
#staticmethod
def get_assignment_types():
return AssignmentType.objects.filter()
I can comment that line and do python manage.py makemigrations, but I wonder what is wrong ? Can someone shed some light?
Error is in this line
AssignmentType.objects.filter(semester=Semester.get_current_semester())
You have to do proper migrations for model Semester
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.
I'm having trouble adding any data to my database. It lets me modify entries in tables, but any action that will create a new row or new column in a database is mysteriously failing. Here is the stack trace:
Traceback (most recent call last):
File "manage.py", line 25, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/management/commands/migrate.py", line 107, in handle
ignore_ghosts = ignore_ghosts,
File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/__init__.py", line 219, in migrate_app
success = migrator.migrate_many(target, workplan, database)
File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/migrators.py", line 235, in migrate_many
result = migrator.__class__.migrate_many(migrator, target, migrations, database)
File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/migrators.py", line 310, in migrate_many
result = self.migrate(migration, database)
File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/migrators.py", line 134, in migrate
self.done_migrate(migration, database)
File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/migrators.py", line 113, in done_migrate
self.record(migration, database)
File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/migrators.py", line 280, in record
record.save()
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/base.py", line 463, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/base.py", line 551, in save_base
result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/manager.py", line 203, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/query.py", line 1576, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/sql/compiler.py", line 910, in execute_sql
cursor.execute(sql, params)
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/backends/util.py", line 40, in execute
return self.cursor.execute(sql, params)
File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/backends/postgresql_psycopg2/base.py", line 52, in execute
return self.cursor.execute(query, args)
django.db.utils.DatabaseError: syntax error at or near "RETURNING" at character 171
It was working fine until I migrated databases to another server. Now I'm having all sorts of trouble and I'm unsure what to do. Also, this seems to happen for South as well if trying to add a field to the database. Curiously, modifying existing objects / columns in the database succeeds without failure. I'm really unsure what to do and would love any assistance.
8.1 doesn't support the RETURNING clause. So upgrade your database version to the current stable release.
8.1 doesn't support RETURNING ids of inserted objects so you need to disable it.
from django.db import connection
##just before insert statement
connection.features.can_return_id_from_insert = False
###some insert statement