So I have this app I wish to deploy to Heroku. I use django-heroku so it can run my postgres-sql stuff automatically.
I added release: python mannge.py migrate to my Procfile.
After the build, I get a deployment failed error, saying Release command failed. On opening the log, I have this error:
psycopg2.ProgrammingError: cannot cast type timestamp with time zone to integer
LINE 1: ...LUMN "established" TYPE integer USING "established"::integer
^
My model with the established field is like this:
from django.db import models
# Create your models here.
class FederalMinistry(models.Model):
full_name = models.CharField(max_length=400)
short_name = models.CharField(max_length=20)
description = models.TextField()
established = models.PositiveIntegerField()
# logo = models.ImageField(upload_to='fed_min_logos', blank=True, null=True, default='N/A')
current_minister = models.CharField(max_length=500)
permanent_secretary = models.CharField(max_length=500, default='N\A')
headquarters = models.CharField(max_length=100, default='Abuja')
twitter = models.URLField(blank=True, null=True, default='N/A')
website = models.URLField(blank=True, null=True, default='N/A')
class Meta:
verbose_name_plural = 'Federal Ministries'
def __str__(self):
return self.full_name
Please why am I getting the error and his to fix it. I have no knowledge of postgres.
Here is the full traceback as was requested:
/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
""")
Operations to perform:
Apply all migrations: admin, airports, auth, contenttypes, federal_ministries, sessions, states, universities
Running migrations:
Applying federal_ministries.0002_auto_20190310_0129...Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: cannot cast type timestamp with time zone to integer
LINE 1: ...LUMN "established" TYPE integer USING "established"::integer
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 203, in handle
fake_initial=fake_initial,
File "/app/.heroku/python/lib/python3.6/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 "/app/.heroku/python/lib/python3.6/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 "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 523, in alter_field
old_db_params, new_db_params, strict)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 122, in _alter_field
new_db_params, strict,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 663, in _alter_field
params,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 133, in execute
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
Q File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to integer
LINE 1: ...LUMN "established" TYPE integer USING "established"::integer
And here is the federal_ministries.0002_auto_20190310_0129 migration file:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('federal_ministries', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='federalministry',
options={'verbose_name_plural': 'Federal Ministries'},
),
migrations.AlterField(
model_name='federalministry',
name='established',
field=models.PositiveIntegerField(),
),
]
And the dependency 0001_initial file:
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='FederalMinistry',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('full_name', models.CharField(max_length=400)),
('short_name', models.CharField(max_length=20)),
('description', models.TextField()),
('established', models.DateTimeField()),
('current_minister', models.CharField(max_length=500)),
('permanent_secretary', models.CharField(default='N\\A', max_length=500)),
('headquarters', models.CharField(default='Abuja', max_length=100)),
('twitter', models.URLField(blank=True, default='N/A', null=True)),
('website', models.URLField(blank=True, default='N/A', null=True)),
],
),
]
I got it. I just needed to reset my migrations and delete the db.sqlite file, then ran migrations and migrate again. Fixed it!
If you are trying to cast a timestamp to PositiveIntegerField in PostgreSQL, you have to know that you can't.
Use a DateTimeField instead of a PositiveIntegerField for enstablished.
I think that this is related, take a look for further infos.
Related
I have a postgresql database and I am making a migration to switch my pk from username to uuid.
I already made a data migration file where I add a uuid to every row in my model
it worked fine on sqlite but when I was testing it on postgresql I got an error.
The error was "django.db.utils.ProgrammingError: column "username" is in a primary key"
I am not sure where to begin to debug this thing. Here is the model, data migration, migration, and stack trace of the error:
# models.py
class UserInformation(models.Model):
uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False)
username = models.CharField(max_length=100, unique=True, blank=True, null=True)
# data migration 42
import uuid
from django.db import migrations
def set_uuid_for_all_user_information(apps, schema_editor):
UserInformation = apps.get_model('accounts', 'UserInformation')
for userInformation_user in UserInformation.objects.all():
userInformation_user.uuid = uuid.uuid4().hex
userInformation_user.save()
class Migration(migrations.Migration):
dependencies = [
('accounts', '0041_auto_20211227_2113'),
]
operations = [
migrations.RunPython(set_uuid_for_all_user_information),
]
# migration 43 (this is where the postgresqsl error occurs) trying to change pk from username to uuid
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('accounts', '0042_auto_20211229_2319'),
]
operations = [
migrations.AlterField(
model_name='userinformation',
name='user',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='auth.user'),
),
migrations.AlterField(
model_name='userinformation',
name='username',
field=models.CharField(blank=True, max_length=100, null=True, unique=True),
),
migrations.AlterField(
model_name='userinformation',
name='uuid',
field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
),
]
when running python manage.py migrate, I get this error:
Tracking file by folder pattern: migrations
Operations to perform:
Apply all migrations: account, accounts, admin, auth, contenttypes, legal, sessions, sites, socialaccount
Running migrations:
Applying accounts.0043_auto_20211229_2321...Traceback (most recent call last):
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.InvalidTableDefinition: column "username" is in a primary key
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\..\python\helpers\pycharm\django_manage.py", line 52, in <module>
run_command()
File "C:\..\python\helpers\pycharm\django_manage.py", line 46, in run_command
run_module(manage_file, None, '__main__', True)
File "C:\..\Python\Python38\lib\runpy.py", line 207, in run_module
return _run_module_code(code, init_globals, run_name, mod_spec)
File "C:\..\Python\Python38\lib\runpy.py", line 97, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "C:\..\Python\Python38\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\..\my_site\manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\..\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\..\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\..\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\..\venv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\..\venv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\..\venv\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "C:\..\venv\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:\..\venv\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:\..\venv\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\..\venv\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\..\venv\lib\site-packages\django\db\migrations\operations\fields.py", line 244, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "C:\..\venv\lib\site-packages\django\db\backends\base\schema.py", line 608, in alter_field
self._alter_field(model, old_field, new_field, old_type, new_type,
File "C:\..\venv\lib\site-packages\django\db\backends\postgresql\schema.py", line 196, in _alter_field
super()._alter_field(
File "C:\..\venv\lib\site-packages\django\db\backends\base\schema.py", line 765, in _alter_field
self.execute(
File "C:\..\venv\lib\site-packages\django\db\backends\base\schema.py", line 145, in execute
cursor.execute(sql, params)
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\..\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "username" is in a primary key
I was thinking of solving this with raw SQL in the database, but I wasn't sure if that would cause further problems or not. I would much rather fix it with a django fix instead of raw sql
Hi AugustusCaesar,
When you remove UUID that time there UUID already migrated files present in migrations folder. So in a simple way, you on the local server first take backup then drop this database...
for backup.
pg_dumpall -U postgres > c:\pgbackup\all.sql
sudo su postgres
drop database database_name
psql livedx_qa < /home/Documents/database_name.sql <- again dump DB
python3 manage.py makemigrations
python3 manage.py migrate
I also face this issue you can use this solution. You can't delete manually migrations files this is not the right way so !!!!!
Thank You!!!
I just added new imageField to my Item model. Then run the command makemigrations, after migrate command i started to get "sqlite3.OperationalError: no such column: REFERRED.id". Then i deleted changes and try to migrate and still have the same error. i tried all the same discussions before, but nothing changes. still have the same error. So i can not add any field because of this error
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length = 2)
label = models.CharField(choices=LABEL_CHOICES, max_length = 1)
slug = models.SlugField()
description = models.TextField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('core:''product', kwargs={
'slug': self.slug
})
def get_add_to_cart_url(self):
return reverse('core:''add-to-cart', kwargs={
'slug': self.slug
})
def get_remove_from_cart_url(self):
return reverse('core:''remove-from-cart', kwargs={
'slug': self.slug
})
This is traceback:
(env) PS C:\Users\User\desktop\dj-projects\django_project_boilerplate> python manage.py migrate
Operations to perform:
Apply all migrations: account, admin, auth, contenttypes, core, sessions, sites, socialaccount
Running migrations:
Applying core.0013_auto_20191119_2152...Traceback (most recent call last):
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\utils.py", line 82, in _execute
return self.cursor.execute(sql)
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 381, in execute
return Database.Cursor.execute(self, query)
sqlite3.OperationalError: no such column: REFERRED.id
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\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\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\core\management\base.py", line 364, in execute
output = self.handle(*args, **options)
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle
fake_initial=fake_initial,
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\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\desktop\dj-projects\django_project_boilerplate\env\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\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\migrations\executor.py", line 247, in apply_migration
migration_recorded = True
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 34, in __exit__
self.connection.check_constraints()
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 341, in check_constraints
column_name, referenced_column_name,
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\utils.py", line 99, in execute
return super().execute(sql, params)
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\utils.py", line 82, in _execute
return self.cursor.execute(sql)
File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 381, in execute
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: no such column: REFERRED.id
Here's 0013 migrtaion
# Generated by Django 2.2 on 2019-11-19 16:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0012_auto_20191114_0053'),
]
operations = [
migrations.RemoveField(
model_name='order',
name='id',
),
migrations.AddField(
model_name='order',
name='order_id',
field=models.AutoField(default='1', primary_key=True, serialize=False),
preserve_default=False,
),
]
Here's 0014 auto migrations
# Generated by Django 2.2 on 2019-11-19 16:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0013_auto_20191119_2152'),
]
operations = [
migrations.RemoveField(
model_name='order',
name='order_id',
),
migrations.AddField(
model_name='order',
name='id',
field=models.AutoField(auto_created=True, default='1', primary_key=True, serialize=False, verbose_name='ID'),
preserve_default=False,
),
]
I developed an API using Django Rest Framework.
I just changed my model in order to link my object to User object of Django by adding creationUser and updateUser :
class Document(models.Model):
name = models.CharField(max_length=100)
recipient = models.ForeignKey('Client', models.SET_NULL, null=True, verbose_name='Client')
provider = models.ForeignKey('Provider', models.SET_NULL, null=True, verbose_name='Provider')
type = models.CharField(max_length=50)
receptionDate = models.DateField()
fileName = models.CharField(max_length=200)
comment = models.TextField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
status = models.CharField(max_length=5)
creationDate = models.DateTimeField(auto_now_add=True, editable=False)
updateDate = models.DateTimeField(auto_now=True)
creationUser = models.ForeignKey(User, models.SET_NULL, null=True, related_name='creationUser') # New Line
updateUser = models.ForeignKey(User, models.SET_NULL, null=True, related_name='updateUser') # New Live
def __str__(self):
return "Id : {0} | Nom : {1} | Fournisseur : {2} | Type : {3} | Date de reception : {4}".format(self.id, self.name, self.provider, self.type, self.receptionDate)
Then I execute :
pipenv run python manage.py makemigrations
pipenv run python manage.py migrate
First line works, but second line provides :
Operations to perform:
Apply all migrations: admin, api, auth, contenttypes, inbox, sessions
Running migrations:
Applying api.0027_auto_20180721_0106...Traceback (most recent call last):
File "manage.py", line 17, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
utility.execute()
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\base.py", line 335, in execute
output = self.handle(*args, **options)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle
fake_initial=fake_initial,
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\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\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\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\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\migrations\migration.py", line 122, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
field,
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\backends\base\schema.py", line 407, in add_field
definition, params = self.column_sql(model, field, include_default=True)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\backends\base\schema.py", line 152, in column_sql
default_value = self.effective_default(field)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\backends\base\schema.py", line 224, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\models\fields\related.py", line 936, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\models\fields\__init__.py", line 767, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\models\fields\__init__.py", line 939, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\models\fields\__init__.py", line 947, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'User'
I can't understand the Reason. I tried to remove creationUser and updateUser and run the two commands again but the issue keep happenning.
As requested by Bernard Parah, here is the api.0027_auto_20180721_0106.py file :
# Generated by Django 2.0.3 on 2018-07-20 23:06
from django.conf import settings
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0026_case_description'),
]
operations = [
migrations.AddField(
model_name='document',
name='creationUser',
field=models.ForeignKey(default=django.contrib.auth.models.User, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='creationUser', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='document',
name='updateUser',
field=models.ForeignKey(default=django.contrib.auth.models.User, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='updateUser', to=settings.AUTH_USER_MODEL),
),
]
There's something wrong in your migration file.
field=models.ForeignKey(default=django.contrib.auth.models.User, ...
There should be no default argument there, and User is not a proper value for default in any case. I don't know what might have happened, since the default are not in your Document model. Try removing both default=django.contrib.auth.models.User, from the migration file and run manage.py migrate again.
You can also try to just delete the migration file and rebuild it with makemigrations
I migrated to sqlite3 to postgresql database and i tried to migrate but it will always throw a exception I am also using drf.
Here is my output:
Operations to perform:
Apply all migrations: admin, auth, authtoken, contenttypes, sessions
Running migrations:
Applying contenttypes.0002_remove_content_type_name...Traceback (most recent call last):
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: column "name" of relation "django_content_type" does not exist
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 515, in alter_field
old_db_params, new_db_params, strict)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field
new_db_params, strict,
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field
params,
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "name" of relation "django_content_type" does not exist
My Bucketlist model has the following code:
class Bucketlist(models.Model):
"""This class represents the bucketlist model."""
name = models.CharField(max_length=255, blank=False, unique=True)
owner = models.ForeignKey(
'auth.User',
related_name='bucketlists',
on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __str__(self):
"""Return a human readable representation of the model instance."""
return "{}".format(self.name)
# This receiver handles token creation when a new user is created.
#receiver(post_save, sender=User)`enter code here`
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
You can try these solutions,
Either you dump/flush your database if you can afford to. And then try to migrate to PostgreSQL.
Follow these steps:
Dump your database to JSON.
./manage.py dumpdata --natural-primary --natural-foreign > data.json
Change the settings for default database in settings.py i.e. switch to PostgreSQL.
Sync the database.
./manage.py migrate
Load the data that you stored in data.json
./manage.py loaddata data.json
I have a model:
class Season(models.Model):
""" Corresponds to your brochure publishing schedule, e.g. Fall/Winter 2012, Sprint 2014, etc. """
name = models.CharField(max_length=45, db_index=True, unique=True)
start_date = models.DateField(db_index=True, help_text="The date enrollment can begin this Season.")
<snip>
The model pre-dates migrations and I didn't use South.
The start_date field lived for many years with this definition
start_date = models.DateField(db_index=True, default=False,
help_text="The date of the first Session of this Season.")
I actually went in to edit the help text and noticed the default=False and thought, that doesnt make sense for a date field, it must have been a remnant from when I was dumb.
So I took that out.
Now my migration:
class Migration(migrations.Migration):
dependencies = [
('district', '0012_auto_20160622_1741'),
]
operations = [
migrations.AlterField(
model_name='season',
name='start_date',
field=models.DateField(help_text=b'The date enrollment can begin this Season.', db_index=True),
),
]
Fails with:
Applying district.0013_auto_20170204_1811...Traceback (most recent call last):
File "manage.py", line 9, in <module>
execute_from_command_line(sys.argv)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv
self.execute(*args, **cmd_options)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute
output = self.handle(*args, **options)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration
state = migration.apply(state, schema_editor)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 484, in alter_field
old_db_params, new_db_params, strict)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 566, in _alter_field
old_default = self.effective_default(old_field)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 211, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
prepared=False)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1322, in get_db_prep_value
value = self.get_prep_value(value)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1317, in get_prep_value
return self.to_python(value)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1274, in to_python
parsed = parse_date(value)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/utils/dateparse.py", line 60, in parse_date
match = date_re.match(value)
TypeError: expected string or buffer
Researching TypeError: expected string or buffer comes up with a discussion about not doing what I'm trying to undo, i.e, don't set the default for a date field to something not date-like.
Not clear how to proceed with this. Any tips would be appreciated.
Determine what the default is in the database
cd /path/to/project
python manage.py dbshell
mysql> show create table district_season\G
# or for postgres
# pg_dump -t 'schema.district_season' --schema-only database-name
If there is no problem with the type, run the migration with --fake
./manage.py migrate district --fake
which will mark the migration as having been run without doing anything to the database.