I switch to Django 1.7. When I try makemigrations for my application, it crash. The crash report is:
Migrations for 'roadmaps':
0001_initial.py:
- Create model DataQualityIssue
- Create model MonthlyChange
- Create model Product
- Create model ProductGroup
- Create model RecomendedStack
- Create model RecomendedStackMembership
- Create model RoadmapMarket
- Create model RoadmapUser
- Create model RoadmapVendor
- Create model SpecialEvent
- Create model TimelineEvent
- Create model UserStack
- Create model UserStackMembership
- Add field products to userstack
- Add field viewers to userstack
- Add field products to recomendedstack
- Add field product_group to product
- Add field vendor to product
- Add field product to dataqualityissue
Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemigrations.py", line 124, in handle
self.write_migration_files(changes)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemigrations.py", line 152, in write_migration_files
migration_string = writer.as_string()
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 129, in as_string
operation_string, operation_imports = OperationWriter(operation).serialize()
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 80, in serialize
arg_string, arg_imports = MigrationWriter.serialize(item)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 245, in serialize
item_string, item_imports = cls.serialize(item)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 310, in serialize
return cls.serialize_deconstructed(path, args, kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 221, in serialize_deconstructed
arg_string, arg_imports = cls.serialize(arg)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 323, in serialize
raise ValueError("Cannot serialize function: lambda")
ValueError: Cannot serialize function: lambda
I found a note about that here https://code.djangoproject.com/ticket/22892
There is also link to documentation https://docs.djangoproject.com/en/dev/topics/migrations/#serializing-values
But it does not make it clearer for me. The error meassage have not gave me a clue where to look for problem.
Is there way how to detect what line exactly cause the problem?
Any hints?
We had this issue with using lambda in the custom field definition.
It is than hard to spot as it is not listed in traceback and the error is not raised on the particular model which uses such custom field.
Our way to fix:
check all your custom fields (even in the 3rd party libraries)
change the lambda to callable, which is defined in the module (i.e. not in custom field class)
It took me a bit of time to figure this out, but a code example of what #Radek suggested.
An example replacing the lambda with a function.
Borken version:
class SomeModel(ParentModel):
thing_to_export = ArrayField(models.CharField(max_length=50),
default=lambda: ['Default thing'])
Working version:
def default_thing():
return ['THIS IS A DEFAULT']
class SomeModel(ParentModel):
thing_to_export = ArrayField(models.CharField(max_length=50),
default=default_thing)
Related
I have a similar problem to this post but its only answer didn't help:
❯ python manage.py makemigrations
No changes detected
Because when I execute python manage.py migrate I get the following traceback:
❯ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, portfolio, sessions
Traceback (most recent call last):
File "C:\Users\user\Projects\personal_website\src\packages\pweb_django\manage.py", line 23, in <module>
main()
File "C:\Users\user\Projects\personal_website\src\packages\pweb_django\manage.py", line 19, in main execute_from_command_line(sys.argv)
File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
utility.execute()
File "C:\Users\user\Projects\personal_website\pweb-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\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 460, in execute
output = self.handle(*args, **options)
File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\commands\migrate.py", line 236, in handle
pre_migrate_apps = pre_migrate_state.apps
File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\utils\functional.py", line 49, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\db\migrations\state.py", line 544, in apps
return StateApps(self.real_apps, self.models)
File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\db\migrations\state.py", line 615, in __init__
raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'portfolio.user', but app 'portfolio' doesn't provide model 'user'.
Yet, when I check the file portfolio\models.py it clearly provides the 'user'-model:
class User(AbstractUser):
"""Dummy class in order to mimic a standard Auth-user.
Docs: https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project
"""
pass
In the related portfolio\admin.py - file, the following admin site is being registered:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)
I would like to understand why this does not work while the other model-class can be found and registered without an issue:
from django.contrib import admin
from .models import Project
admin.site.register(Project)
It happens if you ran default auth app migrations and later changed the AUTH_USER_MODEL in settings.py. You can try following:
#comments AUTH_USER_MODEL in the settings.py file so it points to a default User Model
Python manage.py migrate auth zero
#Uncomment AUTH_USER_MODEL='recommend.AuthUser'
Python manage.py migrate auth
Source
If it's doesn't solve your problems and you are using Sqlite3 you can:
Delete all migration files except __init__.py file.
I am working with django-tenant-schemas and when I try to use "migrate_schemas" command I encounter an error. I've seen similar questions here but they didn't help at all. I've tried this on two different apps but the result is the same. Does anybody know how to fix this?
Traceback (most recent call last):
File "C:\DjangoNew\tenancy\manage.py", line 22, in <module>
main()
File "C:\DjangoNew\tenancy\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 322, in run_from_argv
parser = self.create_parser(argv[0], argv[1])
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 296, in create_parser
self.add_arguments(parser)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\tenant_schemas\management\commands\migrate_schemas.py", line 20, in add_arguments
command.add_arguments(parser)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 28, in add_arguments
help='Skip system checks.',
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1373, in add_argument
return self._add_action(action)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1736, in _add_action
self._optionals._add_action(action)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1577, in _add_action
action = super(_ArgumentGroup, self)._add_action(action)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1387, in _add_action
self._check_conflict(action)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1526, in _check_conflict
conflict_handler(action, confl_optionals)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1535, in _handle_conflict_error
raise ArgumentError(action, message % conflict_string)
argparse.ArgumentError: argument --skip-checks: conflicting option string: --skip-checks
It is a bug in django-tenant-schemas.
From reading Django documents it seems like they forgot to set requires_system_checks to False.
I believe this pull request will fix the problem.
Till this fix is merged, you can solve this by either downgrade Django to version 2 by running something like
pip install "Django~=2.2"
or move tenant-schemas at the INSTALLED_APPS list to the bottom in the settings.py file.
Error: argparse.ArgumentError: argument --email: conflicting option string: --email
If anyone here by this error from django-rest-framework
So, this error occurs because the field 'email' is required, but still in Model's REQUIRED_FIELDS list.
Just remove it from REQUIRED_FIELDS, it should work.
This scenario also possible in other attributes also.
class UserAccount(AbstractUser):
first_name = ...
last_name = ...
email = models.EmailField(_("Email address"), unique=True, blank=False)
REQUIRED_FIELDS = AbstractUser.REQUIRED_FIELDS + ['first_name', 'last_name', 'email']
class Meta(AbstractUser.Meta):
swappable = "AUTH_USER_MODEL"
verbose_name = _("UserAccount")
verbose_name_plural = _("UserAccounts")
based on my model:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
Base = declarative_base()
class Session(Base):
__tablename__ = 'sessions'
id = Column(Integer, primary_key=True)
token = Column(String(200))
user_id = Column(Integer, ForeignKey('app_users.id'))
user = relationship('model.user.User', back_populates='sessions')
I want to instantiate a new session through:
session = Session(token='test-token-123')
But i get:
AttributeError: mapper
The full stacktrace:
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.5/site-packages/falcon/api.py", line 227, in __call__
responder(req, resp, **params)
File "./app_user/register.py", line 13, in on_post
session = Session(token='test-token-123')
File "<string>", line 2, in __init__
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/instrumentation.py", line 347, in _new_state_if_none
state = self._state_constructor(instance, self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/util/langhelpers.py", line 764, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/instrumentation.py", line 177, in _state_constructor
self.dispatch.first_init(self, self.class_)
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/event/attr.py", line 256, in __call__
fn(*args, **kw)
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/mapper.py", line 2976, in _event_on_first_init
configure_mappers()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/mapper.py", line 2872, in configure_mappers
mapper._post_configure_properties()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/mapper.py", line 1765, in _post_configure_properties
prop.init()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/interfaces.py", line 184, in init
self.do_init()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/relationships.py", line 1653, in do_init
self._process_dependent_arguments()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/relationships.py", line 1710, in _process_dependent_arguments
self.target = self.mapper.mapped_table
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/util/langhelpers.py", line 850, in __getattr__
return self._fallback_getattr(key)
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/util/langhelpers.py", line 828, in _fallback_getattr
raise AttributeError(key)
I have no idea where this error is coming from and i can not really debug it.. anybody could help me with this issue?
Thanks and Greetings!
Looking at the traceback you can see these lines:
...
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/relationships.py", line 1653, in do_init
self._process_dependent_arguments()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/relationships.py", line 1710, in _process_dependent_arguments
self.target = self.mapper.mapped_table
...
which narrow your problem down quite a bit. The relationship
user = relationship('model.user.User', back_populates='sessions')
uses a Python evaluable string as the argument, the use of which is further explained in "Configuring Relationships":
Relationships to other classes are done in the usual way, with the added feature that the class specified to relationship() may be a string name. The “class registry” associated with Base is used at mapper compilation time to resolve the name into the actual class object, which is expected to have been defined once the mapper configuration is used
If you've not imported models.user module anywhere before you try to instantiate a Session object for the first time, then the name resolving fails because the class User has not been created yet and does not exist in the registry. In other words for the name resolving to work, all classes must have been defined, which means that their bodies must have been executed.
And if you actually have imported the models.user module, check your other models and that their related model classes have been defined. Using your models for the first time triggers mapper compilation/configuration, so the source of the error could be other models as well.
This problem randomly started appearing for me. I know that Django generates its own ids but a lot my code has been using custom AutoFields which HAS been working. I added a new class today and tried to makemigrations but this error keeps showing up.
I DID remove all instances of AutoFields and retried migrating but the problem still persists which leads me to believe it's something else... I don't believe my Django version has changed at all...
Error:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
338, in execute_from_command_line
utility.execute()
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 390,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 441,
in execute
output = self.handle(*args, **options)
File "C:\Python34\lib\site-packages\django\core\management\commands\makemigrat
ions.py", line 98, in handle
loader.project_state(),
File "C:\Python34\lib\site-packages\django\db\migrations\loader.py", line 326,
in project_state
return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self
.unmigrated_apps))
File "C:\Python34\lib\site-packages\django\db\migrations\graph.py", line 231,
in make_state
project_state = self.nodes[node].mutate_state(project_state, preserve=False)
File "C:\Python34\lib\site-packages\django\db\migrations\migration.py", line 8
3, in mutate_state
operation.state_forwards(self.app_label, new_state)
File "C:\Python34\lib\site-packages\django\db\migrations\operations\fields.py"
, line 51, in state_forwards
state.reload_model(app_label, self.model_name_lower)
File "C:\Python34\lib\site-packages\django\db\migrations\state.py", line 152,
in reload_model
self.apps.render_multiple(states_to_be_rendered)
File "C:\Python34\lib\site-packages\django\db\migrations\state.py", line 262,
in render_multiple
model.render(self)
File "C:\Python34\lib\site-packages\django\db\migrations\state.py", line 546,
in render
body,
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 189, in __
new__
new_class.add_to_class(obj_name, obj)
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 324, in ad
d_to_class
value.contribute_to_class(cls, name)
File "C:\Python34\lib\site-packages\django\db\models\fields\__init__.py", line
989, in contribute_to_class
"A model can't have more than one AutoField."
AssertionError: A model can't have more than one AutoField.
Here's an example of one of my fields:
assetid = models.AutoField(primary_key=True)
A lot of my code already depends on the name itself so changing it is going to be a big issue. Furthermore, this was working perfectly before! I just can't seem to migrate it now. I should mention im using a sqlite3 db.
This is Because Django By default uses AutoField for the id.....so, if you want other fields to be AutoField, then make sure you confirm primary_key=True.
Doing so deletes the id field from the Database.
I have used Mysql as my database. Be sure this problem might not solve in other databases.
Deleted migration files and most recent history and fixed it.
I was having the same problem,
I commented out all the references to that model in all my app files, then run makemigrations and migrate, butit keeps telling that "A model can't have more than one AutoField." even if i am trying to deleting that file.
I had to reset my database.
in my case I deleted id Autofield ,it works fine for me as Django uses Autofield by default
better way is just unapply migrations(meaning run a previous migration).in this way the fields which sometimes are not removed from database are automatically removed from database.Then, after changes you can easily do makemigrations again and then migrate and everything will be good.
I have a problem with south migrations. I still don't understand how this did happen, and what should what path to move to resolve this
Romans-MacBook-Pro:holms$ ./manage.py migrate
cRunning migrations for accounts:
- Nothing to migrate.
- Loading initial data for accounts.
No fixtures found.
Running migrations for allocations:
- Nothing to migrate.
- Loading initial data for allocations.
No fixtures found.
Running migrations for adyen:
- Nothing to migrate.
- Loading initial data for adyen.
No fixtures found.
Running migrations for blog:
- Nothing to migrate.
- Loading initial data for blog.
No fixtures found.
Running migrations for offers:
- Nothing to migrate.
- Loading initial data for offers.
No fixtures found.
Running migrations for orders:
- Migrating forwards to 0011_update_price_fields.
> orders:0002_update_order_contact_information
Traceback (most recent call last):
File "./manage.py", line 15, in <module>
execute_manager(settings)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/Users/holms/Development/xxx/xxx/settings/../../lib/south/management/commands/migrate.py", line 105, in handle
ignore_ghosts = ignore_ghosts,
File "/Users/holms/Development/xxx/xxx/settings/../../lib/south/migration/__init__.py", line 191, in migrate_app
success = migrator.migrate_many(target, workplan, database)
File "/Users/holms/Development/xxx/xxx/settings/../../lib/south/migration/migrators.py", line 221, in migrate_many
result = migrator.__class__.migrate_many(migrator, target, migrations, database)
File "/Users/holms/Development/xxx/xxx/settings/../../lib/south/migration/migrators.py", line 292, in migrate_many
result = self.migrate(migration, database)
File "/Users/holms/Development/xxx/xxx/settings/../../lib/south/migration/migrators.py", line 125, in migrate
result = self.run(migration)
File "/Users/holms/Development/xxx/xxx/settings/../../lib/south/migration/migrators.py", line 99, in run
return self.run_migration(migration)
File "/Users/holms/Development/xxx/xxx/settings/../../lib/south/migration/migrators.py", line 81, in run_migration
migration_function()
File "/Users/holms/Development/xxx/xxx/settings/../../lib/south/migration/migrators.py", line 57, in <lambda>
return (lambda: direction(orm))
File "/Users/holms/Development/xxx/migrations/0002_update_order_contact_information.py", line 29, in forwards
for o in orders:
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 107, in _result_iter
self._fill_cache()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 772, in _fill_cache
self._result_cache.append(self._iter.next())
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 273, in iterator
for row in compiler.results_iter():
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 680, in results_iter
for rows in self.execute_sql(MULTI):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/util.py", line 34, in execute
return self.cursor.execute(sql, params)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 234, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.DatabaseError: no such column: orders_order.pre_paid
part of migration file [0002_update_order_contact_information.py] which breaks:
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
Order = models.get_model('orders', 'Order')
orders = Order.all_objects.select_related('buyer')
orders = orders.filter(first_name__isnull=True)
orders = orders.filter(buyer__isnull=False)
orders = orders.exclude(payment_status="UNFINISHED")
userfields = (
'gender', 'birth_date', 'first_name', 'last_name', 'street_number',
You should not interact with your models directly like that. You use django.models, but that version of the models are in a wrong state. You want the state of the models as they were in migration 0002. The south manual states that you should access your models through the orm parameter.
Notice that we use orm.User to access the User model - this gives us the version of User from when this migration was created, so if we want to run the migration in future, it won’t get a completely different, new, User model. source
So you should rewrite the migration like this:
orders = orm.Order.objects.all()
Or even like this:
Order = orm.Order