I'm trying to run Selenium tests for a Django app on production server.
I am getting a syntax error on the finally: clause.
I don't see where the error is and all the tests ran fine in development.
Here is the code:
def activate_revision(self, user, revision):
self.title = revision.title
self.tagnames = revision.tagnames
self.body = self.rendered(revision.body)
self.active_revision = revision
# Try getting the previous revision
try:
prev_revision = NodeRevision.objects.get(node=self, revision=revision.revision-1)
update_activity = True
# Do not update the activity if only the tags are changed
if prev_revision.title == revision.title and prev_revision.body == revision.body \
and prev_revision.tagnames != revision.tagnames and not settings.UPDATE_LATEST_ACTIVITY_ON_TAG_EDIT:
update_activity = False
except NodeRevision.DoesNotExist:
update_activity = True
finally:
if update_activity:
self.update_last_activity(user)
self.save()
Here is the traceback:
$ python manage.py test forum
Traceback (most recent call last):
File "/usr/lib/python2.4/logging/__init__.py", line 731, in emit
msg = self.format(record)
File "/usr/lib/python2.4/logging/__init__.py", line 617, in format
return fmt.format(record)
File "/usr/lib/python2.4/logging/__init__.py", line 408, in format
s = self._fmt % record.__dict__
KeyError: 'funcName'
/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/db/models/fields/subclassing.py:80: DeprecationWarning: A Field class whose get_db_prep_lookup method hasn't been updated to take `connection` and `prepared` arguments.
new_class = super(SubfieldBase, cls).__new__(cls, name, bases, attrs)
/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/db/models/fields/subclassing.py:80: DeprecationWarning: A Field class whose get_db_prep_value method hasn't been updated to take `connection` and `prepared` arguments.
new_class = super(SubfieldBase, cls).__new__(cls, name, bases, attrs)
Traceback (most recent call last):
File "manage.py", line 13, in ?
execute_manager(settings)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/home/spirituality/lib/python2.7/South-0.7.3-py2.7.egg/south/management/commands/test.py", line 8, in handle
super(Command, self).handle(*args, **kwargs)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/core/management/commands/test.py", line 37, in handle
failures = test_runner.run_tests(test_labels)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/test/simple.py", line 358, in run_tests
suite = self.build_suite(test_labels, extra_tests)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/test/simple.py", line 247, in build_suite
app = get_app(label)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 129, in get_app
self._populate()
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/spirituality/webapps/spirituality/spirit_app/forum/models/__init__.py", line 2, in ?
from question import Question ,QuestionRevision, QuestionSubscription
File "/home/spirituality/webapps/spirituality/spirit_app/forum/models/question.py", line 1, in ?
from base import *
File "/home/spirituality/webapps/spirituality/spirit_app/forum/models/base.py", line 349, in ?
from node import Node, NodeRevision, NodeManager
File "/home/spirituality/webapps/spirituality/spirit_app/forum/models/node.py", line 383
finally:
^
SyntaxError: invalid syntax
First part of the traceback suggests that it's Python 2.4 on production. As per my comment above, the problem is that try..except..finally is only for Python 2.5 and newer. Upgrade production or rewrite the code to nest try..except inside an outer try..finally.
Related
I have a django application with djongo as a database driver. My model is simple:
from django.db import models
from djongo.models import ObjectIdField
class TmpModel(models.Model):
_id = ObjectIdField()
is_deleted = models.BooleanField(default=False)
When I run in shell simple filter command:
>>> TmpModel().save()
>>> TmpModel(is_deleted=True).save()
>>> TmpModel.objects.filter(is_deleted=False).all()
I got an error:
(0.000) QUERY = 'SELECT "solutions_tmpmodel"."_id", "solutions_tmpmodel"."is_deleted" FROM "solutions_tmpmodel" WHERE NOT "solutions_tmpmodel"."is_deleted" LIMIT 21' - PARAMS = (); args=(); alias=default
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse
return handler(self, statement)
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 933, in _select
return SelectQuery(self.db, self.connection_properties, sm, self._params)
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 116, in __init__
super().__init__(*args)
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__
self.parse()
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 152, in parse
self.where = WhereConverter(self, statement)
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\converters.py", line 27, in __init__
self.parse()
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\converters.py", line 119, in parse
self.op = WhereOp(
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\operators.py", line 476, in __init__
self.evaluate()
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\operators.py", line 465, in evaluate
op.evaluate()
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\operators.py", line 258, in evaluate
self.rhs.negate()
AttributeError: 'NoneType' object has no attribute 'negate'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\cursor.py", line 51, in execute
self.result = Query(
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__
self._query = self.parse()
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 885, in parse
raise exe from e
djongo.exceptions.SQLDecodeError:
Keyword: None
Sub SQL: None
FAILED SQL: SELECT "solutions_tmpmodel"."_id", "solutions_tmpmodel"."is_deleted" FROM "solutions_tmpmodel" WHERE NOT "solutions_tmpmodel"."is_deleted" LIMIT 21
Params: ()
Version: 1.3.6
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\cursor.py", line 59, in execute
raise db_exe from e
djongo.database.DatabaseError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\django\db\models\query.py", line 370, in __repr__
data = list(self[: REPR_OUTPUT_SIZE + 1])
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\django\db\models\query.py", line 394, in __iter__
self._fetch_all()
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\django\db\models\query.py", line 1866, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\django\db\models\query.py", line 87, in __iter__
results = compiler.execute_sql(
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\django\db\models\sql\compiler.py", line 1398, in execute_sql
cursor.execute(sql, params)
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\django\db\backends\utils.py", line 103, in execute
return super().execute(sql, params)
s.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\cursor.py", line 59, in execute
raise db_exe from e
django.db.utils.DatabaseError
How to find out what is wrong?
It seems like an issue with Djongo's Boolean SQL condition parsing (GitHub issue #562). For now, the solution is to use __in query:
TmpModel.objects.filter(is_deleted__in=[False]).all()
This has been fixed in djongo#8587ea7 (as of Dec 2022, there's no planned release).
pip install git+https://github.com/doableware/djongo.git#8587ea766e4610da5f31112f7b134699e2d603ee
Workaround for Djongo <= 1.3.6 from doableware/djongo#562 (comment 892486144):
from djongo.base import DatabaseWrapper
from djongo.operations import DatabaseOperations
class PatchedDatabaseOperations(DatabaseOperations):
def conditional_expression_supported_in_where_clause(self, expression):
return False
DatabaseWrapper.ops_class = PatchedDatabaseOperations
Use djongo's model fields for all fields you have instead of django fields
from djongo import models
class TmpModel(models.Model):
_id = models.ObjectIdField()
is_deleted = models.BooleanField(default=False)
We have done Django Upgrade from 1.11 to 2.2 version, we have almost completed, but there is one issue is present, when we run migrations by using the command python manage.py makemigrations
then we are getting following error.
but when we follow the below link issue is resolved.
Migrations error in django 2; AttributeError: 'str' object has no attribute 'decode'
but, I just want to know is there any other way to resolve this issue? I am feeling like there will be library to update which is causing this issue?
When we add manually as suggested in above link, its working fine, but we have docker integration to the project, then it will fail?
same issue is not happening with below django 2.2 and above 2.2.20 versions.
Error message is:
(env4) user2#SK385 pro % python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle
loader.check_consistent_history(connection)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history
applied = recorder.applied_migrations()
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations
if self.has_table():
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/ddtrace/contrib/django/db.py", line 65, in cursor
return DbApiTracedCursor(conn._datadog_original_cursor(), pin)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/backends/base/base.py", line 256, in cursor
return self._cursor()
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/backends/base/base.py", line 233, in _cursor
self.ensure_connection()
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection
self.connect()
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect
self.init_connection_state()
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 231, in init_connection_state
if self.features.is_sql_auto_is_null_enabled:
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/backends/mysql/features.py", line 82, in is_sql_auto_is_null_enabled
cursor.execute('SELECT ##SQL_AUTO_IS_NULL')
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/ddtrace/contrib/dbapi/__init__.py", line 90, in execute
return self._trace_method(self.__wrapped__.execute, self._self_datadog_name, query, {}, query, *args, **kwargs)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/ddtrace/contrib/dbapi/__init__.py", line 44, in _trace_method
return method(*args, **kwargs)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/backends/utils.py", line 103, in execute
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/backends/mysql/operations.py", line 146, in last_executed_query
query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'
user2
I think you're hitting this issue because you're using PyMySQL.
The issue was fixed in ticket 30380, but wasn't backported to Django 2.2.X because Django doesn't officially support PyMySQL.
Some options are:
Upgrade to Django 3.0.X+
Switch from PyMySQL to mysqlclient
patch your version of Django 2.2 (see the fix here)
I'm trying to integrate django-celery into an existing site and I'm coming up against an error that I can't seem to get fixed.
For context, I went through the Django first steps and the test project was successful, ie everything worked as it should.
Now, in my existing project, I can't get the celery worker running from the command line:
manage.py celery worker --loglevel=info --settings=myproject.settings.dev_settings
When i run that I get the following stack trace and error:
Traceback (most recent call last):
File "C:\sites\corecrm\manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 453, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\djcelery\management\commands\celery.py", line 22, in run_from_argv
['%s %s' % (argv[0], argv[1])] + argv[2:],
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 901, in execute_from_commandline
super(CeleryCommand, self).execute_from_commandline(argv)))
File "C:\Python27\lib\site-packages\celery\bin\base.py", line 187, in execute_from_commandline
return self.handle_argv(prog_name, argv[1:])
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 893, in handle_argv
return self.execute(command, argv)
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 868, in execute
return cls(app=self.app).run_from_argv(self.prog_name, argv)
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 148, in run_from_argv
return self(*args, **options)
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 118, in __call__
ret = self.run(*args, **kwargs)
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 220, in run
return self.target.run(*args, **kwargs)
File "C:\Python27\lib\site-packages\celery\bin\celeryd.py", line 153, in run
return self.app.Worker(**kwargs).run()
File "C:\Python27\lib\site-packages\celery\apps\worker.py", line 162, in run
self.app.loader.init_worker()
File "C:\Python27\lib\site-packages\celery\loaders\base.py", line 130, in init_worker
self.import_default_modules()
File "C:\Python27\lib\site-packages\djcelery\loaders.py", line 138, in import_default_modules
self.autodiscover()
File "C:\Python27\lib\site-packages\djcelery\loaders.py", line 141, in autodiscover
self.task_modules.update(mod.__name__ for mod in autodiscover() or ())
File "C:\Python27\lib\site-packages\djcelery\loaders.py", line 176, in autodiscover
for app in settings.INSTALLED_APPS])
File "C:\Python27\lib\site-packages\djcelery\loaders.py", line 195, in find_related_module
return importlib.import_module('%s.%s' % (app, related_name))
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\sites\corecrm\people\tasks.py", line 15, in <module>
from people.models import Customer, CustomerCsvFile, CustomerToTag, get_customer_from_csv_row
File "C:\sites\corecrm\people\models.py", line 163, in <module>
UserProfile._meta.get_field_by_name('username')[0]._max_length = 75
File "C:\Python27\lib\site-packages\django\db\models\options.py", line 351, in get_field_by_name
cache = self.init_name_map()
File "C:\Python27\lib\site-packages\django\db\models\options.py", line 380, in init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "C:\Python27\lib\site-packages\django\db\models\options.py", line 469, in get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "C:\Python27\lib\site-packages\django\db\models\options.py", line 483, in _fill_related_many_to_many_cache
for klass in get_models(only_installed=False):
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 197, in get_models
self._populate()
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 75, in _populate
self.load_app(app_name)
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in import_module
__import__(name)
File "C:\sites\corecrm\booking\models.py", line 17, in <module>
from people.models import Customer, UserProfile
ImportError: cannot import name Customer
To try and work out what the booking/models.py script sees in people I added the following at the start:
import people
print 'path: %s' % people.__path__
for item in dir(people):
print item
and that gives me the following output:
path: ['C:\\sites\\corecrm\\people']
__builtins__
__doc__
__file__
__name__
__package__
__path__
path: ['C:\\sites\\corecrm\\people']
__builtins__
__doc__
__file__
__name__
__package__
__path__
however, when I run manage.py shell --settings=myproject.settings.dev_settings I get the following output:
path: ['C:\\sites\\corecrm\\people']
__builtins__
__doc__
__file__
__name__
__package__
__path__
path: ['C:\\sites\\corecrm\\people']
__builtins__
__doc__
__file__
__name__
__package__
__path__
models
As you can see the models module is available at the end of the 2nd list for the shell command (and I've confirmed this is also the case for manage.py commands other than celery). How would I make sure that module is available at the same point when I run the celery command?
EDIT: I've now also set up this project on an Ubuntu VM and I'm getting the same error when I try to run the worker manage command. Any ideas? Anyone?
ANOTHER EDIT: I've pasted the code for booking/models.py and people/models.py at http://pastebin.com/fTVVBtB4
I'm pretty sure this line is your problem:
File "C:\sites\corecrm\people\models.py", line 163, in <module>
UserProfile._meta.get_field_by_name('username')[0]._max_length = 75
While you're still busy importing from people.models, this line (in particular get_field_by_name) forces Django to evaluate the model and setup all relationships between that model and it's related models. This, in turn, forces an import of Customer in people.models, while you're still busy importing that exact model. This is what results in an ImportError.
For a working solution you'll need to post your models.py.
Why does this error only occur with celery? I can't say for sure without some more information, but my best guess is that Celery handles importing everything slightly different (Django probably doesn't import Customer, CustomerCsvFile, CustomerToTag and get_customer_from_csv_row all at once) and that this exposes the bug in your code.
EDIT/SOLUTION:
I would remove this line:
UserProfile._meta.get_field_by_name('username')[0]._max_length = 75
And move it to the instance level, into the __init__ method:
class UserProfile(AbstractUser):
def __init__(self, *args, **kwargs):
self._meta.get_field_by_name('username')[0]._max_length = 75
super(UserProfile, self).__init__(*args, **kwargs)
If the cause of the issue is indeed what I think it is, this will fix the circular import while providing the same functionality. If the max_length functionality gets broken somehow (most likely because internally a max_length validator is added to CharField and _max_length is changed too late) I would instead override the complete username field in the init method:
class UserProfile(AbstractUser):
def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs)
self._meta.get_field_by_name('username')[0] = models.CharField(max_length=75, etc.)
So, I am learning to use South and I've been running in a few issues. I did the initial app migration with the model looking like this:
class Poll(models.Model):
pass
Then added my fields...
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField()
and during the migration South complained that those fields didn't have a default, so I entered some but it didn't work... now when I try deleting them from the model and migrating back to the empty mode I get the following traceback:
mirkocrocop#Mirkos-MacBook-Pro:~/workspace/toastdriven$ python manage.py migrate polls
Running migrations for polls:
- Migrating forwards to 0007_auto__del_field_poll_question.
> polls:0003_auto__add_field_poll_question__add_field_poll_pub_date
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/management/commands/migrate.py", line 108, in handle
ignore_ghosts = ignore_ghosts,
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/__init__.py", line 213, in migrate_app
success = migrator.migrate_many(target, workplan, database)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 235, in migrate_many
result = migrator.__class__.migrate_many(migrator, target, migrations, database)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 310, in migrate_many
result = self.migrate(migration, database)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 133, in migrate
result = self.run(migration)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 106, in run
dry_run.run_migration(migration)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 191, in run_migration
self._run_migration(migration)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 178, in _run_migration
raise exceptions.FailedDryRun(migration, sys.exc_info())
south.exceptions.FailedDryRun: ! Error found during dry run of '0003_auto__add_field_poll_question__add_field_poll_pub_date'! Aborting.
Traceback (most recent call last):
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 175, in _run_migration
migration_function()
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 57, in <lambda>
return (lambda: direction(orm))
File "/Users/mirkocrocop/workspace/toastdriven/polls/migrations/0003_auto__add_field_poll_question__add_field_poll_pub_date.py", line 19, in forwards
keep_default=False)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/db/sqlite3.py", line 31, in add_column
field.column: self._column_sql_for_create(table_name, name, field, False),
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/db/sqlite3.py", line 189, in _column_sql_for_create
sql = self.column_sql(table_name, name, field, with_name=False, field_prepared=True)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/db/generic.py", line 688, in column_sql
default = field.get_db_prep_save(default, connection=self._get_connection())
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 292, in get_db_prep_save
prepared=False)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 816, in get_db_prep_value
value = self.get_prep_value(value)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 801, in get_prep_value
value = self.to_python(value)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 785, in to_python
raise exceptions.ValidationError(msg)
ValidationError: [u"'0' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
How could I fix this, and what is the correct way of adding these fields + doing the migration from the empty model to the field populated model? I've been going through South's docs but I don't get it... I did everything according to the documentation, but I'm not sure what should I default the DateTimeField to...
At the time you have to provide a default value, you are interacting with a python interpreter. As it is mentioned, the datetime module is available at that point in time. To provide a default for a DateTimeField in this case, just provide a datetime object:
# Use the current date and time
datetime.datetime.now()
# Or a specific date and time
datetime.datetime(2012, 10, 1, 17, 30, 0, 0)
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.