Django Migration Error without DateTime field - django

I tried to insert a new field in my model and I got a DateTime Migration error, So I deleted those two fields and am trying to run "migrate" function which is not working , Make migration still work though.
D:\trydjango\src>python manage.py makemigrations
No changes detected
D:\trydjango\src>python manage.py migrate
Operations to perform:
Apply all migrations: contenttypes, auth, sessions, admin, posts
Running migrations:
Rendering model states... DONE
Applying posts.0009_auto_20170213_1754...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\python35\lib\site-packages\django\core\management\__init__.py", line
350, in execute_from_command_line
utility.execute()
File "C:\python35\lib\site-packages\django\core\management\__init__.py", line
342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\python35\lib\site-packages\django\core\management\base.py", line 348,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:\python35\lib\site-packages\django\core\management\base.py", line 399,
in execute
output = self.handle(*args, **options)
File "C:\python35\lib\site-packages\django\core\management\commands\migrate.py
", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 92
, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_ini
tial)
File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 12
1, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_
initial)
File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 19
8, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\python35\lib\site-packages\django\db\migrations\migration.py", line 1
23, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, projec
t_state)
File "C:\python35\lib\site-packages\django\db\migrations\operations\fields.py"
, line 62, in database_forwards
field,
File "C:\python35\lib\site-packages\django\db\backends\sqlite3\schema.py", lin
e 221, in add_field
self._remake_table(model, create_fields=[field])
File "C:\python35\lib\site-packages\django\db\backends\sqlite3\schema.py", lin
e 103, in _remake_table
self.effective_default(field)
File "C:\python35\lib\site-packages\django\db\backends\base\schema.py", line 2
10, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
728, in get_db_prep_save
prepared=False)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1461, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1440, in get_prep_value
value = super(DateTimeField, self).get_prep_value(value)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1296, in get_prep_value
return self.to_python(value)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1399, in to_python
parsed = parse_datetime(value)
File "C:\python35\lib\site-packages\django\utils\dateparse.py", line 93, in pa
rse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
D:\trydjango\src>
Below is my Models.py file.
from django.db import models
from django.core.urlresolvers import reverse
class Invoice(models.Model):
active = models.BooleanField()
bu_field = models.CharField(max_length=10)
invoice_name = models.CharField(max_length=500)
sow_name = models.CharField(max_length=500)
probability = models.IntegerField()
sow_type = models.CharField(max_length=50)
sow_start_date = models.DateField()
sow_end_date = models.DateField()
project_id = models.CharField(max_length=500)
project_manager = models.CharField(max_length=500, null=True)
po_number = models.IntegerField()
sow_value = models.DecimalField(max_digits=8, decimal_places=2)
current_month = models.CharField(max_length=20)
current_year = models.CharField(max_length=5)
month_value = models.DecimalField(max_digits=8, decimal_places=2)
q1_value = models.IntegerField()
q2_value = models.IntegerField()
q3_value = models.IntegerField()
q4_value = models.IntegerField()
total_value_ofyear = models.IntegerField()
probability_month_value = models.IntegerField()
def __str__(self):
return self.invoice_name
def get_absolute_url(self):
return reverse("invoice:detail", kwargs={"id": self.id})
There are no new fields , everything is back as it was but not i am getting this error.

Related

Problem with ForeignKey, Django migrations

When I tried to migrate my project to a different version I faced this error:
ProgrammingError: ERROR: the id column specified in the foreign key constraint does not exist.
UPDATE: This is the full log: The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 23, in <module>
execute_from_command_line(sys.argv)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 200, in handle
fake_initial=fake_initial,
File "/home/user/MyProjects/forest-venv/lib/python3.5/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 "/home/user/MyProjects/forest-venv/lib/python3.5/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 "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/migrations/migration.py", line 122, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/user/MyProjects/forest-venv/lib/python3.5/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/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 525, in alter_field
old_db_params, new_db_params, strict)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/postgresql/schema.py", line 122, in _alter_field
new_db_params, strict,
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 750, in _alter_field
self.execute(self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s"))
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 133, in execute
cursor.execute(sql, params)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
But I don't have an id column in my model:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from renter.models import RefAbstract, Renter
from django.contrib.gis.db import models
from textwrap import shorten
class Unitt(RefAbstract):
....//some classes
class Task(RefAbstract):
class Meta(RefAbstract.Meta):
verbose_name = 'task'
verbose_name_plural = 'tasks'
class Spatial(models.Model):
codeq = models.IntegerField('no',help_text='no')
code = models.PositiveIntegerField('cutare',primary_key=True,help_text='cutare')//unique column
codeV = models.IntegerField('novi',help_text='novi')
renter = models.ForeignKey(Renter, on_delete=models.DO_NOTHING, verbose_name='renter')
geometry = models.MultiPolygonField(geography=True, verbose_name='geometry')
class Meta:
verbose_name = 'cutarea'
verbose_name_plural = 'cutarea'
class LScharacteristic(models.Model):
codels = models.ForeignKey(Spatial, on_delete=models.DO_NOTHING, verbose_name = 'cutarea')// Foreign Key
tract = models.CharField('tract',max_length = 80, help_text='tract')
task = models.ForeignKey(Task, on_delete=models.DO_NOTHING, verbose_name='task')
totalarea = models.PositiveIntegerField('totarea',help_text = 'totarea')
explarea = models.PositiveIntegerField('exarea',help_text = 'exarea')
protecttype = models.CharField('category',max_length = 50, help_text = 'category')
class Meta:
verbose_name = 'characteristic'
verbose_name_plural = 'characteristics'
class PlannedUsing(models.Model):
codels = models.ForeignKey(Spatial, on_delete=models.DO_NOTHING, verbose_name = 'cutarea') // Foreign Key
codeq = models.IntegerField(help_text='number')
cutareaShape = models.ForeignKey(CutareaShape, on_delete=models.DO_NOTHING, verbose_name='form')
cuttype = models.ForeignKey(CutareaType, on_delete=models.DO_NOTHING, verbose_name='type1')
managetype = models.ForeignKey(ManageType, on_delete=models.DO_NOTHING, verbose_name='type2')
unit = models.ForeignKey(Unitt, on_delete=models.DO_NOTHING, verbose_name='unit')
composition = models.ForeignKey(Composition, on_delete=models.DO_NOTHING, verbose_name='sort')
assortment = models.ForeignKey(Assortment, on_delete=models.DO_NOTHING, verbose_name='assort')
class Meta:
verbose_name = 'planus'
verbose_name_plural = 'planuss'
What is the id column and why does it exist if I never defined it?
How I can to fix this?
I think that the problem is that your ForeignKey fields do not point explicitly to the field that you have marked as primary (Spatial.code).
By marking Spatial.code as primary you prevent Django from creating the id field. See the documentation But if you point a ForeignKey to just a model it will try to link to the id field of that model.
To fix this you can add to your ForeignKey field the parameter: to_field='code' and add unique=True to Spatial.code.See documentation
You can use
def __str__(self):
return self.etat
or
def __int__(self):
For specif what do you return on your django model.
like this:
tests= models.CharField(max_length=100, verbose_name="Test")
class Meta:
verbose_name = "Tests"
ordering = ['tests']
def __str__(self):
return self.tests

TypeError: int() argument must be a string, a bytes-like object or a number, not 'User'

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

insert or update on table "page_content_pagesection" violates foreign key constraint

I just made some changes to my Django models locally, made migrations for them, and pushed up those migrations to my production server. Everything works fine locally, but when I try and perform a migrate in the production server, I get this error. The zero index is throwing me off. The model its dependent on, teamsafetytracker is new, and page sections have never depended on it up until now, so I'm not sure why it would even be looking for instances in the teamsafetytracker table ?
django.db.utils.IntegrityError: insert or update on table "page_content_pagesection" violates foreign key constraint "page_co_safety_tracker_id_f30c4360_fk_team_teamsafetytracker_id"
DETAIL: Key (safety_tracker_id)=(0) is not present in table "team_teamsafetytracker".
relevant migrations
class Migration(migrations.Migration):
dependencies = [
('team', '0037_remove_teampagesection_multi_tracker_one'),
]
operations = [
migrations.RemoveField(
model_name='team',
name='safety_clock_start',
),
]
class Migration(migrations.Migration):
dependencies = [
('team', '0038_remove_team_safety_clock_start'),
('page_content', '0017_auto_20170926_1436'),
]
operations = [
migrations.RemoveField(
model_name='webpage',
name='safety_clock_start',
),
migrations.AddField(
model_name='pagesection',
name='multi_tracker_three',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='page_multi_three', to='team.TeamSafetyTracker'),
),
migrations.AddField(
model_name='pagesection',
name='multi_tracker_two',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='page_multi_two', to='team.TeamSafetyTracker'),
),
migrations.AddField(
model_name='pagesection',
name='tracker_side',
field=models.CharField(choices=[(b'L', b'Left'), (b'T', b'Three Section'), (b'R', b'Right')], default=b'R', max_length=20),
),
migrations.AlterField(
model_name='pagesection',
name='safety_tracker',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='page_section', to='team.TeamSafetyTracker'),
),
]
Models
class TeamSafetyTracker(models.Model):
name = models.CharField(max_length=255)
label = models.CharField(max_length=200)
team = models.ForeignKey('Team')
safety_clock_start = models.DateTimeField(help_text="Date Since Last Accident. Used if You Have Page Sections That Include a Safety Tracker", null=True, blank=True)
create_date = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'Team Safety Tracker'
verbose_name_plural = 'Team Safety Trackers'
def __str__(self):
return self.name
class PageSection(models.Model):
page = models.ForeignKey(WebPage)
title = models.CharField(max_length=255, null=True, blank=True)
content = models.TextField(null=True, blank=True)
has_gallery = models.BooleanField(default=False)
gallery = models.ForeignKey('PhotoGallery', null=True, blank=True)
safety_tracker = models.ForeignKey(TeamSafetyTracker, related_name='page_section', null=True, blank=True)
multi_tracker_two = models.ForeignKey(TeamSafetyTracker, related_name='page_multi_two', null=True, blank=True)
multi_tracker_three = models.ForeignKey(TeamSafetyTracker, related_name='page_multi_three', null=True, blank=True)
tracker_side = models.CharField(max_length=20, choices=TRACKER_SIDES, default='R')
background_choices = models.CharField(max_length=100, choices=BACKGROUND_CHOICES, default='WH')
display_order = models.IntegerField(default=1)
is_published = models.BooleanField(default=True)
def __str__(self):
return ('Section %s') % self.display_order
class Meta:
verbose_name = 'Section'
verbose_name_plural = 'Sections'
ordering = ('display_order',)
def gallery_sets(self):
if self.gallery:
gallery_photos = self.gallery.photos.filter(is_published=True)
set_1 = gallery_photos[:10]
gallery_sets = [set_1]
if gallery_photos.count() > 10:
set_2 = gallery_photos[10:20]
gallery_sets.append(set_2)
if gallery_photos.count() > 20:
set_3 = gallery_photos[20:30]
gallery_sets.append(set_3)
if gallery_photos.count() > 30:
set_4 = gallery_photos[30:40]
gallery_sets.append(set_4)
if gallery_photos.count() > 40:
set_5 = gallery_photos[40:50]
gallery_sets.append(set_5)
return gallery_sets
else:
return []
#staticmethod
def get_published_objects():
objects = PageSection.objects.filter(is_published=True).order_by('display_order')
return objects
Traceback
Running migrations:
Rendering model states... DONE
Applying team.0032_teamsafetytracker... OK
Applying team.0033_auto_20180306_1928... OK
Applying team.0034_auto_20180306_1942... OK
Applying team.0035_auto_20180306_1944... OK
Applying team.0036_auto_20180306_1953... OK
Applying team.0037_remove_teampagesection_multi_tracker_one... OK
Applying team.0038_remove_team_safety_clock_start... OK
Applying page_content.0018_auto_20180307_1851...Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: insert or update on table "page_content_pagesection" violates foreign key constraint "page_co_safety_tracker_id_f30c4360_fk_team_teamsafetytracker_id"
DETAIL: Key (safety_tracker_id)=(0) is not present in table "team_teamsafetytracker".
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 "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.5/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.5/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.5/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.5/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python3.5/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.5/dist-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/schema.py", line 482, in alter_field
old_db_params, new_db_params, strict)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/postgresql/schema.py", line 116, in _alter_field
new_db_params, strict,
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/schema.py", line 717, in _alter_field
self.execute(self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s"))
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: insert or update on table "page_content_pagesection" violates foreign key constraint "page_co_safety_tracker_id_f30c4360_fk_team_teamsafetytracker_id"
DETAIL: Key (safety_tracker_id)=(0) is not present in table "team_teamsafetytracker".
This seems to be a problem of old values in that Pagesection table ie. there is a PageSection entry where the safety_tracker is already 0 (This field was previously an IntegerField). When you changed it to a ForeignKey to TeamSafetyTracker Django tried to match that old values with a TeamSafetyTracker ID.
Make sure all the values of the column safety_tracker are set to null before running the page_content.0018_auto_20180307_1851 migration. You can create a custom migration to do that.

Django and postgres migration errors

I have created a new postgressql db in my django app within Heroku. Every time I run a migration, however, I get an error that I don't understand.
Error:
Applying argent.0043_auto_20170322_1629...Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: cannot cast type date to integer
LINE 1: ...LTER COLUMN "date_id" TYPE integer USING "date_id"::integer,...
I have removed and added the only date field I have, to no avail. I still get the same error whether the date field in my models is there or not. Any insight would be much appreciated.
models.py
class Entry(models.Model):
date = models.DateField(blank=True, null=True,)
euros = models.CharField(max_length=500, blank=True, null=True)
comments = models.CharField(max_length=900, blank=True, null=True)
euros_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
xrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
dollars_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
daily_savings_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
daily_savings_display = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
def get_absolute_url(self):
return reverse('argent:detail', kwargs={'pk': self.pk})
def item_date(self):
row_title = self.date
return row_title
class Meta:
ordering = ['date']
traceback:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, 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 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/app/.heroku/python/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 "/app/.heroku/python/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 "/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 129, 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 215, 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 513, 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 112, in _alter_field
new_db_params, strict,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 674, in _alter_field
params,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 119, in execute
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: cannot cast type date to integer
LINE 1: ...LTER COLUMN "date_id" TYPE integer USING "date_id"::integer,...
If want to migrate the date column from a integer type to to a datetime one, you need to handle any existing entries you have in the table before you can run the migration.
It's likely that you already have some integers in the date column when you try to change the column type, so the conversion fails as postgres doesn't know how to convert an integer to a datetime.
You can either delete all your entries if you don't care about them, or otherwise you need to break you migration into separate steps:
Create the new datetime column with a temporary name
Run a data migration to convert your integers into datetimes and populate the new column
Drop the old integer date column, rename the new one with the final name.

python: return int(value) ValueError: invalid literal for int() with base 10: ''

Help, I keep getting ValueError: invalid literal for int() with base
10: '' when I try to migrate my models. this is my model
from django.db import models
from datetime import date
class PoliceAssurance(models.Model):
numPolice = models.AutoField(primary_key=True)
raison = models.CharField(max_length=50)
tel = models.CharField(max_length=20)
email = models.CharField(max_length=50)
interlocuteur = models.CharField(max_length=50)
dateDebut = models.CharField(max_length=50)
dateFin = models.CharField(max_length=50)
tiers = models.CharField(max_length=50)
formule = models.CharField(max_length=50)
territoire = models.CharField(max_length=50)
exclusions = models.CharField(max_length=50)
complement = models.CharField(max_length=50)
this is the trace
Operations to perform:
Apply all migrations: sessions, contenttypes, log, admin, auth
Running migrations:
Rendering model states... DONE
Applying log.0003_auto_20170206_1251...Traceback (most recent call last):
File "manage.py", line 10,in <module> execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line utility.execute()
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 399, in execute output = self.handle(*args, **options) File "C:\Python34\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle executor.migrate(targets,plan, fake=fake,fake_initial=fake_initial)
File "C:\Python34\lib\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 "C:\Python34\lib\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 "C:\Python34\lib\site-packages\django\db\migrations\executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor)
File "C:\Python34\lib\site-packages\django\db\migrations\migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Python34\lib\site-packages\django\db\migrations\operations\fields.py", line 62, in database_forwards field,
File "C:\Python34\lib\site-packages\django\db\backends\base\schema.py", line 382, in add_field definition, params = self.column_sql(model, field, include_default=True)
File "C:\Python34\lib\site-packages\django\db\backends\base\schema.py", line 145, in column_sql default_value = self.effective_default(field)
File "C:\Python34\lib\site-packages\django\db\backends\base\schema.py", line 210, in effective_default default = field.get_db_prep_save(default, self.connection)
File "C:\Python34\lib\site-packages\django\db\models\fields\__init__.py", line 728, in get_db_prep_save prepared=False)
File "C:\Python34\lib\site-packages\django\db\models\fields\__init__.py", line 968, in get_db_prep_value value = self.get_prep_value(value)
File "C:\Python34\lib\site-packages\django\db\models\fields\__init__.py", line 976, in get_prep_value return int(value)
ValueError: invalid literal for int() with base 10: ''
my problem is solved
i delete the migrations folder and I executed these commands
python manage.py showmigrations App
python manage.py migrate zero
python manage.py makemigrations
python manage.py migrate App and i run the App