django 1.9: ProgrammingError: relation "users_user" does not exist - django

I am running into a ProgrammingError when doing migrate, I think it may be related to the use of django-allauth with a custom user. Here is what I do
1/ Create a fresh database with psql:
create database dj_example;
2/ Installed_apps contain django.contrib.sites:
DJANGO_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
)
THIRD_PARTY_APPS = (
'crispy_forms', # Form layouts
'allauth', # registration
'allauth.account', # registration
#'allauth.socialaccount', # registration
#'allauth.socialaccount.providers.twitter',
'djcelery', #Celery
)
LOCAL_APPS = (
'tucat.users', # custom users app
}
3/ site_id is set to 1
SITE_ID = 1
4/ Custom user model is overly simple:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
def __unicode__(self):
return self.username
5/ Makemigrations works fine
# python manage.py makemigrations
Migrations for 'djcelery':
0028_auto_20160601_1919.py:
- Alter field status on taskmeta
6/ Migrate returns ProgrammingError: relation "users_user" does not exist
# python manage.py migrate
Operations to perform:
Apply all migrations: auth, contenttypes, djcelery, account, admin, sessions
Running migrations:
Rendering model states... DONE
Applying account.0001_initial...Traceback (most recent call last):
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "users_user" does not exist
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 12, in <module>
execute_from_command_line(sys.argv)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/antoinet/.virtualenvs/tucat/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/antoinet/.virtualenvs/tucat/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/antoinet/.virtualenvs/tucat/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/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 90, in __exit__
self.execute(sql)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "users_user" does not exist
Any idea of how to resolve that problem?

You have to delete the migrations folder and then, you should do
python manage.py migrate --run-syncdb
python manage.py migrate --fake appname

Your error is caused by the order you run the migrations. Since many apps depend on the user model existing, you must run the initial migrations for your custom user app before those other apps.
If you change the default user model in an existing project, it might be easier to discard all existing migrations (and the database) and rebuild from scratch. The order to apply migrations would be:
The core django.contrib apps.
Your custom user app.
Other custom apps and third party apps.
You can use django-admin showmigrations to see which migrations exists and are planned.

FYI-
I had this problem, and to resolve it I had to comment out all references to views.py in my urls.py and url_tenants.py files. Then, I ran makemigrations and got the database tables to create, then run migrate_schemas, and later uncomment the url files. Hope this helps someone.

Related

Django ProgrammingError in Fields on PostgreSQL

models.py
class Stop(models.Model):
idn = models.PositiveIntegerField(primary_key=True, unique=True)
label = models.CharField(null=False, blank=False, max_length=512)
coor_x = models.FloatField()
coor_y = models.FloatField()
buses = models.ManyToManyField(Bus)
latest_query_datetime = models.DateTimeField(default=datetime(2000, 1, 1, 0, 0, 0))
latest_query_data = JSONField(default={})
class Meta:
ordering = ["label"]
def __str__(self):
return self.label
When I run:
python3 manage.py makemigrations && python3 manage.py migrate
It raises a ProgrammingError saying that jsonb datatype does not exist:
Migrations for 'rest':
0007_auto_20160612_1301.py:
- Alter field latest_query_data on stop
Operations to perform:
Apply all migrations: contenttypes, rest, auth, sessions, admin
Running migrations:
Rendering model states... DONE
Applying rest.0005_auto_20160612_1237...Traceback (most recent call last):
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: type "jsonb" does not exist
LINE 1: ... TABLE "rest_stop" ADD COLUMN "latest_query_data" jsonb DEFA...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/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/erayerdin/.venv/eshot-api/lib/python3.5/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/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/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/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 396, in add_field
self.execute(sql, params)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: type "jsonb" does not exist
LINE 1: ... TABLE "rest_stop" ADD COLUMN "latest_query_data" jsonb DEFA...
I use PostgreSQL to use JSONField and update it when a user requests a view. If I do not use default={}, it tells me to make one.
Further Analysis
I changed latest_query_data field to TextField so that I can store as string and convert to dict when I need. However, this also raised the same error.
Environment
django 1.9.6
psycopg 2.6.1
According to the Django docs, JSONField requires PostgreSQL ≥ 9.4 and Psycopg2 ≥ 2.5.4
What PostgreSQL version are you using?
See https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#django.contrib.postgres.fields.JSONField
Ubuntu 14.04 repositories contain only 9.3 version. You can review this to upgrade your version.
Based on the Anonymous comment, I found the following to work:
from django.contrib.postgres import fields
class OldJSONField(fields.JSONField):
def db_type(self, connection):
return 'json'
class Stop(models.Model):
...
latest_query_data = OldJSONField(default=dict)
...
If you are getting this error and you have installed Postgres > 9.4 then I would check that you aren't connecting to an older version of Postgres that is also installed on your instance.
To confirm what you are connecting to from Django you can use psycopg2 from the shell:
import psycopg2
conn = psycopg2.connect("dbname=<your database> user=<your user> password=<your password>")
cur = conn.cursor()
cur.execute("SELECT Version();")
cur.fetchone()
Make sure the version here is > 9.4. If not you probably have a couple of versions installed and your service configuration is pointing at the other version.
With older versions of PostgreSQL for example "PostgreSQL9.2.x",
We can use an alternative as
from jsonfield import JSONField
instead of:
from django.contrib.postgres.fields import JSONField
for example:
from django.db import models
from jsonfield import JSONField
class MyModel(models.Model):
json = JSONField()
Can install as:
pip install jsonfield
Check this out:
Add support for PostgreSQL 9.2+'s native json type. #32
This solution is especially good for some limited edition versions. For example,
on VPS & Cpanel that supports postgresql9.2 by default
more details!, see"rpkilby-jsonfield"
So, it seems a bug on psycopg2 or django, I will post an issue on both repositories. This is how I've solved (at least, ProgrammingError) the problem.
Change JSONField to TextField.
Flush your database.
Beware! This operation will erase all the data but the structure in your database.
Remove all migrations folder in all of your apps.
Run python3 manage.py makemigrations && python3 manage.py migrate in all of your apps.
Run python manage.py makemigrations <appname> && python3 manage.py migrate <appname> for each app you have.
Use built-in json module to convert between str and dict.
However, remember, this solution requires so much effort if you want to filter a QuerySet of a model. I do not recommend it, but there was no other solution to get rid of this error and all I needed to do was to save data and represent it.
! This answer will be accepted as default if there will not occur any other better solution in 48 hours.

Does makemigrations in django recreates existing tables for a reason?

I wanted to validate if there is a bug in makemigrations in django 1.8 with sql lite or I am doing something wrong.
After I Dropped my DB and deleted all migration folders. I run
python manage.py makemigrations
python manage.py migrate
DB gets created no problems.
2.I have to modify existing model in one of the apps (app abc)
I perform my change and run again
python manage.py makemigrations
3.it doesn't find any changes
then I run same thing again but with app name
python manage.py makemigrations abc
4.It does some updates in migrations , I believe it recreates all the tables and not just my change !!!!
5.Then I execute
python manage.py migrate
and getting error that table already exists .
Is it a bug in django framework or I am doing something wrong and there is a reason why it behaves this way?
Copy paste from my shell starting from step 2:
(mrp) C:\Users\I812624\dev\mrp\src>python manage.py makemigrations
No changes detected
(mrp) C:\Users\I812624\dev\mrp\src>python manage.py makemigrations purchase
Migrations for 'purchase':
0001_initial.py:
- Create model PO
- Create model POmaterial
(mrp) C:\Users\I812624\dev\mrp\src>python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: customer, manufacture, product, django_filters, a
utofixture, staticfiles, messages, smart_selects, watson, sales, item, django_co
untries, mptt, inventory, django_select2, production, main, crispy_forms
Apply all migrations: purchase, vendor, sessions, admin, sites, flatpages, con
tenttypes, auth, registration
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying purchase.0001_initial...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\core\management\__init
__.py", line 338, in execute_from_command_line
utility.execute()
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\core\management\__init
__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\core\management\base.p
y", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\core\management\base.p
y", line 441, in execute
output = self.handle(*args, **options)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\core\management\comman
ds\migrate.py", line 221, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\migrations\executor
.py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=f
ake_initial)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\migrations\executor
.py", line 147, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\migrations\migratio
n.py", line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, projec
t_state)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\migrations\operatio
ns\models.py", line 59, in database_forwards
schema_editor.create_model(model)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\base\schem
a.py", line 282, in create_model
self.execute(sql, params or None)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\base\schem
a.py", line 107, in execute
cursor.execute(sql, params)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\utils.py",
line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\utils.py",
line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\utils.py", line 97,
in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\utils.py",
line 62, in execute
return self.cursor.execute(sql)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\sqlite3\ba
se.py", line 316, in execute
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: table "purchase_po" already exists
To answer my own question .
So what I have figured out . I believe the problem is that I have originally deleted the folders migrations and when I run makemigrations without specifying particular app it does create a DB but it dosent create the folder makemigrations with ____init____.py inside it.
solution each time when you drop db and delete migrations folder for whatever reason dont just delete the migrations folder but only its content excluding init file.
Or when you do delete the folder run make migrations individually for each app as #MicroPyramid suggested.
Without doing deeper investigation it looks to me or as confusing designed behaviour or a bug from Django side.

Recover from failed migration

When running
python3 manage.py migrate
I was asked what the default value of 'id' should be and entered 1. I had read
https://docs.djangoproject.com/en/1.9/howto/writing-migrations/#migrations-that-add-unique-fields
but that was a bit too complicated for me so tried 1.
Now when I run
python3 manage.py migrate
I get the following error:
vagrant#vagrant-ubuntu-trusty-64:/vagrant/grader$ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, core, contenttypes, auth, sessions
Running migrations:
Rendering model states... DONE
Applying core.0002_auto_20160103_1302...Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: multiple default values specified for column "id" of table "core_student"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 342, 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 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/commands/migrate.py", line 200, 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 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python3.4/dist-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/local/lib/python3.4/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python3.4/dist-packages/django/db/migrations/migration.py", line 123, 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/fields.py", line 62, in database_forwards
field,
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/schema.py", line 396, in add_field
self.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "core_student"
How can I recover from this failed migration? I went into the psql command promt and typed
SELECT * FROM core_students
It returned 0 rows so I don'w know why I have a problem.
Shouldn't Django automatically make the 'id' field be unique numbers?
EDIT:
The id has been auto generated by the Django migration.
student model:
class Student(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
owner = models.ForeignKey('auth.User', related_name='students')
identity_number = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
I often run into a similar problem where a migration fails for whatever reason, and only part of it gets applied to the database.
In theory you should be able to go into the database and run queries to finish the migration, but knowing what exact queries to run and what parts of the migration haven't been run is difficult in my experience.
The most dependable way I've found to fix it is to fake the migration, then back up the model, comment it out in models.py, then make a migration to delete it, then fake that as well. Then I can go into the database, drop the table, and then make a new migration to recreate it the way I now want to be.
Here are the commands I run:
python manage.py migrate --fake [appname] #fake the failed migration
#comment out the model in models.py and back up the data
python manage.py makemigrations [appname]
python manage.py migrate --fake [appname] #fake the migration to delete
the table
python manage.py dbshell
#drop the table. Mysql would be: DROP TABLE [appname]_[modelname];
#exit dbshell
#Uncomment the model in models.py adding in whatever changes were originally wanted
python manage.py makemigrations [appname]
python manage.py migrate #assuming your model change is valid, this should work this time.
#reload your data into the table
No, it's not elegant, but it gets django migrations working again without having to guess how far django got through a migration before it failed.

Django migration fails with "__fake__.DoesNotExist: Permission matching query does not exist."

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.

No table south_migrationhistory

I'm trying to use social-auth in django with a Mac Maverick.
This is my INSTALLED_APPS in settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'social_auth',
'south',
)
When I run
python manage.py syncdb
I get this
Syncing...
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Synced:
> django.contrib.auth
> django.contrib.contenttypes
> django.contrib.sessions
> django.contrib.sites
> django.contrib.messages
> django.contrib.staticfiles
> django.contrib.admin
Not synced (use migrations):
- social_auth
- south
(use ./manage.py migrate to migrate these)
So, when I try to migrate social-auth with
python mange.py migrate social_auth
I get this error:
django.db.utils.OperationalError: no such table: south_migrationhistory
When I try
python manage.py migrate
I get this traceback
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/south/management/commands/migrate.py", line 111, in handle
ignore_ghosts = ignore_ghosts,
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/south/migration/__init__.py", line 200, in migrate_app
applied_all = check_migration_histories(applied_all, delete_ghosts, ignore_ghosts)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/south/migration/__init__.py", line 79, in check_migration_histories
for h in histories:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 96, in __iter__
self._fetch_all()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 854, in _fetch_all
self._result_cache = list(self.iterator())
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 710, in results_iter
for rows in self.execute_sql(MULTI):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 781, in execute_sql
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/util.py", line 69, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 450, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: south_migrationhistory
What should I do?
in your lib/python2.7/site-packages/south check if you have a folder migrations. Delete them. That solves the problem.
I don't see a schemamigration command before your migrate. Try:
python manage.py schemamigration social_auth --initial
or
python manage.py schemamigration social_auth --auto
before running the migrate command.