I'm trying to run a migration for my Django project, but I'm getting the error:
AttributeError: 'ManyToManyField' object has no attribute 'm2m_reverse_field_name'
I when I ran make migrations on all my apps, I didn't get any errors. It's only when I try to actually migrate. I can't tell from the traceback information which model is creating the problem, or even which app. I've looked at my models, and I don't see anything that pops out at me.
Here is the stack trace:
Operations to perform:
Apply all migrations: admin, sessions, case_manager, file_manager, auth, contenttypes, tasks, people_and_property
Running migrations:
Rendering model states... DONE
Applying file_manager.0006_auto_20160109_1536...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 467, in alter_field
return self._alter_many_to_many(model, old_field, new_field, strict)
File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 274, in _alter_many_to_many
old_field.remote_field.through._meta.get_field(old_field.m2m_reverse_field_name()),
AttributeError: 'ManyToManyField' object has no attribute 'm2m_reverse_field_name'
How do I figure out which model is the problem? What should I look for?
You have to make sure that the model you are creating the 'ManyToManyField' is already created in the database.
You can do that by adding as a dependency the migration where the model is created to your migration in which you alter the field:
Scenario 1: You alter the field to 'ManyToManyField' with a model from other app
class Migration(migrations.Migration):
dependencies = [
..........
('[app]', '__first__'),
]
operations = [
.........
]
Scenario 2: You create a 'ManyToManyField' and the model you are referring to is in the same file:
class Migration(migrations.Migration):
dependencies = [
..........
]
operations = [
.........
# Make sure the model you are making the reference with is before the ManyToManyField
migrations.CreateModel(...) ,
migrations.AlterField/CreateField(...)
]
I ran into the same problem, but I don’t know if for the same reasons. Luckily I don’t have any important data in the system, so I just changed the migration as follows – but note that this deletes all data in these columns!
Before:
operations = [
migrations.AlterField(
model_name='resource',
name='authors',
field=models.ManyToManyField(related_name='resources_authored', to='api.Person'),
),
migrations.AlterField(
model_name='resource',
name='editors',
field=models.ManyToManyField(blank=True, related_name='resources_edited', to='api.Person'),
),
]
After:
operations = [
migrations.RemoveField(
model_name='resource',
name='authors',
),
migrations.RemoveField(
model_name='resource',
name='editors',
),
migrations.AddField(
model_name='resource',
name='authors',
field=models.ManyToManyField(related_name='resources_authored', to='api.Person'),
),
migrations.AddField(
model_name='resource',
name='editors',
field=models.ManyToManyField(blank=True, related_name='resources_edited', to='api.Person'),
),
]
While the altering failed for mysterious reasons, removing and recreating the fields worked.
One of the reason might be your api.Person model migrations might not have run before the one in which it is referenced(in your example it is file_manager.0006_auto_20160109_1536). So make sure api.Person migrations are run before, by adding them in the dependencies of file_manager.0006_auto_20160109_1536.
I had the same problem when I tried to rename a table which was referenced with a many to many fields.
I resolved it this way:
- dumped the manytomany relationship data into a file
- removed the manytomany field and migrated
- renamed the table and migrated
- added the manytomany field back and migrated and loaded the relationships from the dump
I also had the same problem, but the way that I fixed it, is the following steps:
Nota: You will lose data from that ManyToManyField
python manage.py makemigrations app_name
python manage.py migrate app_name --fake
Don't forget the --fake
After that.
I removed (or just comment the line) the ManyToMany field, and then makemigrations app_name, migrate app_name.
At this step you have this column from your database cleared, what you need to do now is to re add the ManyToManyField, so when you makemigrations app_name & migrate app_name again.
You server can run perfectly
It's not the best, but it worked for me.
hope it will help !
My problem came with changing a field from a choices field to a manytomanyfield.
If you do this and keep the same name, then you'll have issues.
I followed Denis Drescher:
Basically go through your migration files and check what django is doing with these fields.
If django is doing migrations.AlterField for the field which was a choices field and is now a manytomanyfield, change it to
migrations.RemoveField and then Migrations.AddField
I had no meaningful data as yet, so I deleted the database(db.sqlite3) and all migrations(0001,0002 etc)
Simply check if you renamed model-related attributes or anthing related to the model in the admin before you drop the db.
Actually it worked for me.
Related
I created a CustomUser using the Django allAuth package. Allowing users to sign-up and log in via email rather than usernames was the primary reason why.
When I try logging into the admin with my superuser account, it throws this error:
ProgrammingError at /admin/login/
(1146, "Table 'torquedb.showroom_customuser' doesn't exist")
Admin.py for the customuser
#admin.register(CustomUser)
class CustomUserAdmin(admin.ModelAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username', 'phone_number', 'website']
The CustomUser models.py
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
phone_number = models.IntegerField(default='07')
website = models.CharField(max_length=50)
def __str__(self):
return f'{self.name}'
I've tried running new migrations with
py manage.py makemigrations
py manage.py migrate
py manage.py migrate showroom (the app name)
I've already dropped and recreated the MariaDB database (called torquedb) a few times, and this is a new one with all migrations up to date. Again, they all state that they are up to date.
Update
This issue is probably directly related to the custom user I created using Django allauth. When I tried to migrate it, this error was raised:
raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
ValueError: Related model 'showroom.CustomUser' cannot be resolved
Even though all other migrations worked fine. So I ran py manage.py migrate --fake to fake the migration and everything else worked fine.
I know faking migrations doesn't actually make the migrations, which is the problem, but I can't still can't figure out how to solve it.
After purging the database and starting afresh, this is the error produced.
(torque) C:\code\torque>py manage.py makemigrations No changes detected (torque) C:\code\torque>py manage.py migrate showroom Operations to perform: Apply all migrations: showroom Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying showroom.0001_initial... OK Applying account.0001_initial... OK Applying account.0002_email_max_length... OK Applying account.0003_auto_20191015_1328... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying admin.0004_auto_20191015_1328... OK Applying sites.0001_initial... OK Applying socialaccount.0001_initial... OK Applying socialaccount.0002_token_max_lengths... OK Applying socialaccount.0003_extra_data_default_dict... OK Applying socialaccount.0004_auto_20191015_1328... OK Applying showroom.0002_auto_20191015_1328...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 "C:\Users\USER\Envs\torque\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\USER\Envs\torque\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\USER\Envs\torque\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\USER\Envs\torque\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\USER\Envs\torque\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\USER\Envs\torque\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\migrations\operations\fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\backends\base\schema.py", line 507, in alter_field new_db_params = new_field.db_parameters(connection=self.connection) File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\models\fields\related.py", line 966, in db_parameters return {"type": self.db_type(connection), "check": self.db_check(connection)} File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\models\fields\related.py", line 963, in db_type return self.target_field.rel_db_type(connection=connection) File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\models\fields\related.py", line 878, in target_field return self.foreign_related_fields[0] File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\models\fields\related.py", line 632, in foreign_related_fields return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field) File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\models\fields\related.py", line 619, in related_fields self._related_fields = self.resolve_related_fields() File "C:\Users\USER\Envs\torque\lib\site-packages\django\db\models\fields\related.py", line 604, in resolve_related_fields raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'showroom.CustomUser' cannot be resolved
Then I fake the migration
(torque) C:\code\torque>py manage.py migrate --fake showroom Operations to perform: Apply all migrations: showroom Running migrations: Applying showroom.0002_auto_20191015_1328... FAKED Applying showroom.0003_auto_20191015_1329... FAKED
As per documentation on changing to a custom user model mid-project:
Changing AUTH_USER_MODEL after you’ve created database tables is significantly more difficult since it affects foreign keys and many-to-many relationships, for example.
This change can’t be done automatically and requires manually fixing your schema, moving your data from the old user table, and possibly manually reapplying some migrations
So, I think all you need to
Delete all the migration files(which reside in <any app directory>/migration, also don't remove the __init__.py file from the migration directory) from all the apps
Drop the database and create new one.
re-create all the migration using ./manage.py makemigrations and migrate using ./manage.py migrate.
More information can be found in ticket: #25313 where you can do the changes without loosing the data in DB. You can also checkout my blog post as well.
Also looking into your code, probably you should use:
#admin.register(CustomUser)
class CustomUserAdmin(admin.ModelAdmin):
# ^^^^^^^^^^^^^^^^^
When adding the model to admin site.
I have a development database I was working on and I had issues with the migrations taking for adding a foreignkey field. I ended up having to blow away the database after clearing my migrations folder out and redoing it. So now I have one migration file...
The problem is, I pulled code to my test server, and now that database is VERY out of sync (it's not, django thinks it is. It really just needs a table added and a field). Though running make migrations breaks as the migration folder I had pushed was clear of all but one migration and does not jive with the migration folder on the test server.
Any ideas as to how I can reconcile this, it is my test data so blowing away the database here and starting new isn't an issue, but this will be a huge issue again when I push to production (and cannot blow away that database). Maybe dump the data/database using pg_dump, blow away the database, run migrations and load the data back via the dump file?
EDIT:
I did try to create my own migration manually since I was in a state where makemigrations said nothing new was done. My migration file:
The error it gives me (no idea what this is telling me)
Operations to perform:
Apply all migrations: filer, sessions, admin, auth, contenttypes, swsite, registration, easy_thumbnails
Running migrations:
Rendering model states... DONE
Applying swsite.0001_initial... OK
Applying swsite.0002_auto_20170302_0841...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/lib64/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/usr/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/usr/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/lib64/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply
operation.state_forwards(self.app_label, project_state)
File "/usr/lib64/python2.7/site-packages/django/db/migrations/operations/fields.py", line 50, in state_forwards
state.models[app_label, self.model_name_lower].fields.append((self.name, field))
KeyError: (u'swsite', u'cesiumentity')
The migration:
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2017-03-02 15:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.contrib.gis.db.models.fields
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('swsite', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ZoneEntity',
fields=[
('zone_number', models.CharField(max_length=100, primary_key=True, serialize=False)),
('mpoly', django.contrib.gis.db.models.fields.PolygonField(srid=4326)),
('created_at', models.DateField(auto_now_add=True)),
('updated_at', models.DateField(auto_now=True)),
],
),
migrations.AddField(
model_name='cesiumentity',
name='zone_id',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='swsite.ZoneEntity'),
),
]
If this is something you can do manually (add one field and one table), you can set the migrations as completed in the migration table (either all of them, or just the ones that are causing issues).
This might help you out:
https://www.algotech.solutions/blog/python/django-migrations-and-how-to-manage-conflicts/
As you are the single developer for the project, python manage.py migrate should be fine if you are pushing migrations in the git repo.
Or you can ignore migrations folder by adding it to .gitignore and run python manage.py makemigrations on test server every time db is modified and finally u can execute python manage.py migrate to reflect changes in the db.
I have a new field to add to my db. So I say
python manage.py makemigrations
which correctly creates kernel/migrations/0003_auto_20150726_1911.py. I inspect the contents and all looks good.
I say
python manage.py migrate
and I am less happy. The file kernel/migrations/0002_auto_20150707_1459.py, which adds field date_of_birth to table userprofile, fails. Even though I'm pretty sure that migration is applied. And so migration 0003 is never applied.
This is production. :(
I'm not at all sure what to do in order to apply 0003 and not hose django. Suggestions?
The rest of this is supporting docs:
The migrations
╭╴ (master=) [virt]╶╮
╰ [T] django#beta13:migrations $ cat 0002_auto_20150707_1459.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('kernel', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='date_of_birth',
field=models.DateField(null=True, blank=True),
),
]
╭╴ (master=) [virt]╶╮
╰ [T] django#beta13:migrations $ cat 0003_auto_20150726_1911.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('kernel', '0002_auto_20150707_1459'),
]
operations = [
migrations.AddField(
model_name='trippending',
name='requesting_user',
field=models.ForeignKey(default=1, related_name='trippending_requesting', to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
migrations.AddField(
model_name='userprofile',
name='can_see_pending_trips',
field=models.BooleanField(default=False),
),
]
╭╴ (master=) [virt]╶╮
╰ [T] django#beta13:migrations $
The error
(The site runs in French, but I think the error is clear anyway.)
╭╴ (master %=) [virt]╶╮
╰ [T] django#beta13:django $ python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages, admindocs
Apply all migrations: admin, sessions, custom_user, auth, kernel, contenttypes, registration, sites
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying kernel.0002_auto_20150707_1459...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 221, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/src/django/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
File "/src/django/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 147, in apply_migration
state = migration.apply(state, schema_editor)
File "/src/django/venv/lib/python3.4/site-packages/django/db/migrations/migration.py", line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/src/django/venv/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/src/django/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 484, in alter_field
old_db_params, new_db_params, strict)
File "/src/django/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 571, in _alter_field
old_default = self.effective_default(old_field)
File "/src/django/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 211, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/src/django/venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
prepared=False)
File "/src/django/venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1322, in get_db_prep_value
value = self.get_prep_value(value)
File "/src/django/venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1317, in get_prep_value
return self.to_python(value)
File "/src/django/venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1287, in to_python
params={'value': value},
django.core.exceptions.ValidationError: ["Le format de date de la valeur «\xa0\xa0» n'est pas valide. Le format correct est AAAA-MM-JJ."]
╭╴ (master %=) [virt]╶╮
╰ 1,[T] django#beta13:django $
The data
I checked with postgres, expecting to find something amiss. But all looks fine.
mydb=# select date_of_birth from kernel_userprofile;
date_of_birth
---------------
2018-10-23
1972-05-31
1978-10-21
2008-12-29
1967-08-26
2015-07-26
(6 rows)
mydb=#
For the community, the issue was django_migrations table was not updated with 0002_auto_20150707_1459 even though the migration was actually applied on table as mentioned in the post.
The solution was to insert a new row in django_migrations table with data like below so migration 0002 was skipped.
INSERT INTO DJANGO_MGRATIONS ('app', 'name', 'applied') VALUES ('appname', '0002_auto_20150707_1459', '2015-07-07 00:00')
Skipping migration must be done with extreme caution, hence check all details before skipping.
Same trouble happend, but without any logs
At first I determined what app was a problem, by running
python manage.py migrate app_name
for every django app
after that I check migrations for app by running
python manage.py showmigrations app_name
And marked first uncompleted migration as completed by running
python manage.py migrate --fake app_name migration_name
※ about fake
And that was a solution in my case
For anyone finding this post: I just helped a coworker debug a similar problem (same error message), and in this case the source of the problem was trying to give the DateField a default value of u"" (which is of course invalid for a date) instead of None.
Actually part of the fun was that the previous migration (which created the model) already had this wrong default but still ran seamlessly, the error only appearing when trying to alter the field in any way.
The fix required editing the previous migration to set the sane default value, since Django uses the previous migration's schema description to get the previous default value.
In a Django 1.8 project, I have a migration that worked fine, when it had the following code:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.conf import settings
def update_site_forward(apps, schema_editor):
"""Add group osmaxx."""
Group = apps.get_model("auth", "Group")
Group.objects.create(name=settings.OSMAXX_FRONTEND_USER_GROUP)
def update_site_backward(apps, schema_editor):
"""Revert add group osmaxx."""
Group = apps.get_model("auth", "Group")
Group.objects.get(name=settings.OSMAXX_FRONTEND_USER_GROUP).delete()
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.RunPython(update_site_forward, update_site_backward),
]
This group is created in a migration, because it shall be available in all installations of the web app. To make it more useful, I wanted to also give it a default permission, so I changed update_site_forward to:
def update_site_forward(apps, schema_editor):
"""Add group osmaxx."""
Group = apps.get_model("auth", "Group")
Permission = apps.get_model("auth", "Permission")
ContentType = apps.get_model("contenttypes", "ContentType")
ExtractionOrder = apps.get_model("excerptexport", "ExtractionOrder")
group = Group.objects.create(name=settings.OSMAXX_FRONTEND_USER_GROUP)
content_type = ContentType.objects.get_for_model(ExtractionOrder)
permission = Permission.objects.get(codename='add_extractionorder',
content_type=content_type) # line 16
group.permissions.add(permission)
and Migration.dependencies to:
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('excerptexport', '0001_initial'),
('auth', '0001_initial'),
]
While applying the migration (after first reverting it) (python3 manage.py migrate auth 0001 && python3 managy.py migrate) worked, migrating a newly created PostgreSQL database with this and all other migrations (python3 manage.py migrate) fails:
Operations to perform:
Synchronize unmigrated apps: debug_toolbar, django_extensions, messages, humanize, social_auth, kombu_transport_django, staticfiles
Apply all migrations: excerptexport, admin, sites, contenttypes, sessions, default, stored_messages, auth
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying auth.0002_add_default_usergroup_osmaxx...Traceback (most recent call last):
File "manage.py", line 17, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/base.py", line 393, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/base.py", line 444, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/commands/migrate.py", line 221, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python3.4/dist-packages/django/db/migrations/executor.py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python3.4/dist-packages/django/db/migrations/executor.py", line 148, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python3.4/dist-packages/django/db/migrations/migration.py", line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/local/lib/python3.4/dist-packages/django/db/migrations/operations/special.py", line 183, in database_forwards
self.code(from_state.apps, schema_editor)
File "/home/osmaxx/source/osmaxx/contrib/auth/migrations/0002_add_default_usergroup_osmaxx.py", line 16, in update_site_forward
permission = Permission.objects.get(codename='add_extractionorder', content_type=content_type)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 334, in get
self.model._meta.object_name
__fake__.DoesNotExist: Permission matching query does not exist.
What am I doing wrong?
The default permissions are created in a post_migrate signal handler, after the migrations have run. This won't be a problem if your updated code runs as part of the second manage.py migrate run, but it is a problem in the test suite and any new deployment.
The easy fix is to change this line:
permission = Permission.objects.get(codename='add_extractionorder',
content_type=content_type) # line 16
to this:
permission, created = Permission.objects.get_or_create(codename='add_extractionorder',
content_type=content_type)
The signal handler that creates the default permissions will never create a duplicate permission, so it is safe to create it if it doesn't exist already.
Im trying to migrate my django model:
from django.contrib.auth.models import User
class Post(models.Model):
headline = models.CharField(max_length=200)
slug = models.SlugField(max_length=200)
body = models.TextField(blank=True, null=True)
author = models.ForeignKey(User, null=True, blank=True)
I added the author field after I created the model.
Here is the migration django creates:
# encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [('articles', '0002_auto')]
operations = [
migrations.AddField(
field = models.ForeignKey(to_field=u'id', to=u'auth.User', blank=True, null=True),
name = 'author',
model_name = 'post',
),
]
Here is my traceback when I try to run ./manage.py migrate:
Operations to perform:
Synchronize unmigrated apps: ckeditor, sessions, admin, messages, auth, staticfiles, contenttypes, django_extensions
Apply all migrations: articles
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Installed 0 object(s) from 0 fixture(s)
Running migrations:
Applying articles.0002_post_author...Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/__init__.py", line 397, in execute_from_command_line
utility.execute()
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/__init__.py", line 390, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/base.py", line 289, in execute
output = self.handle(*args, **options)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/commands/migrate.py", line 116, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/executor.py", line 60, in migrate
self.apply_migration(migration, fake=fake)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/executor.py", line 73, in apply_migration
migration.apply(project_state, schema_editor)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/migration.py", line 80, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/operations/fields.py", line 22, in database_forwards
schema_editor.add_field(from_model, to_model._meta.get_field_by_name(self.name)[0])
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/backends/schema.py", line 349, in add_field
definition, params = self.column_sql(model, field, include_default=True)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/backends/schema.py", line 105, in column_sql
db_params = field.db_parameters(connection=self.connection)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 1285, in db_parameters
return {"type": self.db_type(connection), "check": []}
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 1276, in db_type
rel_field = self.related_field
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 1183, in related_field
return self.foreign_related_fields[0]
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 971, in foreign_related_fields
return tuple(rhs_field for lhs_field, rhs_field in self.related_fields)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 958, in related_fields
self._related_fields = self.resolve_related_fields()
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 943, in resolve_related_fields
raise ValueError('Related model %r cannot been resolved' % self.rel.to)
ValueError: Related model u'auth.User' cannot been resolved
Anyone know what I'm doing wrong?
What helped me in this situation:
Delete all migration files except __init__.py (/%prjname%/migrations folder)
python manage.py makemigrations
python manage.py migrate
Not sure about exact cause, but i tried to use files, generated by my code-partner and it didn't work out.
Ok, this is another funky feature of Django which cost me hours to figure it out. According to https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#substituting-a-custom-user-model:
Due to limitations of Django’s dynamic dependency feature for swappable models, you must ensure that the model referenced by AUTH_USER_MODEL is created in the first migration of its app (usually called 0001_initial); otherwise, you will have dependency issues.
So to solve this problem the best "clean" way is to put your custom user model creation in 0001_initial.py and it will simply work. And that's the real reason why Lebedev Sergey's delete/makemigrations trick can work.
If you make this change after you have applied ANY other migrations, you need to delete everything else in the migration folder and then run "python manage.py makemigrations". Then whatever you used for AUTH_USER_MODEL will be your first migration.
This probably isn't your problem if you're not using a custom user model, but remember to always use get_user_model() or when referencing the User class. Also, when defining a foreign key, settings.AUTH_USER_MODEL works, too, as in:
class MyModel(models.Model):
person = models.ForeignKey(settings.AUTH_USER_MODEL)