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
Related
When I'm trying to make migrations of my models in Django, I keep getting the same error, even after I've commented out all the changes:
(.venv) C:\Users\jezdo\venv\chat\chat_proj>python manage.py makemigrations chat
Migrations for 'chat':
chat\migrations\0002_alter_customusergroup_custom_group_name_and_more.py
- Alter field custom_group_name on customusergroup
- Alter field users on customusergroup
Traceback (most recent call last):
File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 22, in <module>
main()
File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
utility.execute()
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 448, in execute
output = self.handle(*args, **options)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 239, in handle
self.write_migration_files(changes)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 278, in write_migration_files
migration_string = writer.as_string()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 141, in as_string
operation_string, operation_imports = OperationWriter(operation).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 99, in serialize
_write(arg_name, arg_value)
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 63, in _write
arg_string, arg_imports = MigrationWriter.serialize(_arg_value)
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 282, in serialize
return serializer_factory(value).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 221, in serialize
return self.serialize_deconstructed(path, args, kwargs)
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 99, in serialize_deconstructed
arg_string, arg_imports = serializer_factory(arg).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize
item_string, item_imports = serializer_factory(item).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize
item_string, item_imports = serializer_factory(item).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 386, in serializer_factory
raise ValueError(
ValueError: Cannot serialize: <User: jezdo>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/4.1/topics/migrations/#migration-serializing
my model in models.py:
class CustomUserGroup(models.Model):
custom_group_name = models.CharField(max_length=50, unique=True)
users= MultiSelectField(max_length=100,choices=users_list,unique=False)
class Meta:
verbose_name_plural = 'Custom Groups'
ordering = ['custom_group_name']
def __unicode__(self):
return self.custom_group_name
I wanted to create another model similar to CustomUserGroup byt with a different "users" field:
class CustomUserGroup2(models.Model):
custom_group_name = models.CharField(max_length=50, unique=True)
users= models.ManyToManyField(User)
class Meta:
verbose_name_plural = 'Custom Groups'
ordering = ['custom_group_name']
def __unicode__(self):
return self.custom_group_name
but couldn't makemigrations due to the described error. Now I cannot make any migrations whatsoever, even after having deleted the CustomUserGroup2 class.
I'm using Python 3.10.4 and Django 4.1.6.
When attempting to migrate my database in Django. I receive the following:
Running migrations:
Applying shop.0002_transactions...Traceback (most recent call last):
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/parler/models.py", line 942, in contribute_translations
base = shared_model._parler_meta
AttributeError: type object 'Product' has no attribute '_parler_meta'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 233, in handle
fake_initial=fake_initial,
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/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 "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/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 "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/migration.py", line 114, in apply
operation.state_forwards(self.app_label, project_state)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/operations/models.py", line 86, in state_forwards
list(self.managers),
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 96, in add_model
self.reload_model(app_label, model_name)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 157, in reload_model
self._reload(related_models)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 190, in _reload
self.apps.render_multiple(states_to_be_rendered)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 307, in render_multiple
model.render(self)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 578, in render
return type(self.name, bases, body)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/models/base.py", line 320, in __new__
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 338, in register_model
self.do_pending_operations(model)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/apps/registry.py", line 424, in do_pending_operations
function(model)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/apps/registry.py", line 403, in apply_next_model
self.lazy_model_operation(next_function, *more_models)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/apps/registry.py", line 389, in lazy_model_operation
function()
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/models/fields/related.py", line 317, in resolve_related_class
field.do_related_class(related, model)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/models/fields/related.py", line 388, in do_related_class
self.contribute_to_related_class(other, self.remote_field)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/parler/fields.py", line 58, in contribute_to_related_class
self.model.contribute_translations(cls)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/parler/models.py", line 944, in contribute_translations
raise TypeError("Translatable model {} does not appear to inherit from TranslatableModel".format(shared_model))
TypeError: Translatable model <class '__fake__.Product'> does not appear to inherit from TranslatableModel
I do not understand what the issue is preventing me from migrating the database.
Any help is appreciated.
My models.py file
from django.db import models
from django.urls import reverse
from parler.models import TranslatableModel, TranslatedFields
class Category(TranslatableModel):
translations = TranslatedFields(
name = models.CharField(max_length=200, db_index=True),
slug = models.SlugField(max_length=200, db_index=True,
unique=True)
)
class Meta:
# ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_list_by_category', args=[self.slug])
class Product(TranslatableModel):
translations = TranslatedFields(name = models.CharField(max_length=200,
db_index=True), slug = models.SlugField(max_length=200, db_index=True),
description = models.TextField(blank=True))
category = models.ForeignKey(Category, related_name='products',
on_delete=models.CASCADE)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail', args=[self.id, self.slug])
I do not understand what the issue may be. Here is my admin.py also. I believe the disconnect is between these two files after I make migrations and attempt to migrate.
from django.contrib import admin
from .models import Category, Product
from parler.admin import TranslatableAdmin
#admin.register(Category)
class CategoryAdmin(TranslatableAdmin):
list_display = ['name', 'slug']
def get_prepopulated_fields(self, request, obj=None):
return {'slug': ('name',)}
#admin.register(Product)
class ProductAdmin(TranslatableAdmin):
list_display = ['name', 'slug', 'price', 'available', 'created',
'updated']
list_filter = ['available', 'created', 'updated']
list_editable = ['price', 'available']
def get_prepopulated_fields(self, request, obj=None):
return {'slug': ('name',)}
I think the solution to this problem is in the same book you are working from.
Have you read this and made sure you changed the two occurences, not only one?
Edit the file migrations/0002_translations.py of the shop application and replace the two occurrences of the following line:
Copy
bases=(parler.models.TranslatedFieldsModelMixin, models.Model),
with the following one:
Copy
bases=(parler.models.TranslatableModel, models.Model),
This is a fix for a minor issue found in the django-parler version you are using. This change is necessary to prevent the migration from failing when applying it. This issue is related to creating translations for existing fields in the model and will probably be fixed in newer django-parler versions.
As far as I could see, the answer is that "parler" is currently broken. I ran into the same problem as you and even though I also tried to follow the documentation (and NOT the book!) at django-parler.readthedocs.io, the result was a COMPLETELY destroyed set of migrations, which I then had to painfully delete and rebuilt from scratch (always make complete backups BEFORE you do anything that touches migrations!).
I have opened a case with the Django Parler team #GitHub, but I have so far not received any answer. I believe this product is no longer maintained, or they have too many other things to work on.
In the end I ignored anything that used "Django-parler" in the book and jumped to the next section.
Once I will be working on my own product, I will most likely have to try other solutions from djangopackages.org
I know this is not the solution you were looking for, but I believe it is the correct answer, since "parler" simply seems to be broken at this point in time.
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.
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.
This is what my models.py looks like:
from django.db import models
from django.core.validators import RegexValidator
# Create your models here.
class Customer(models.Model):
customer_id = models.AutoField(primary_key=True,unique=True)
full_name = models.CharField(max_length=50)
user_email = models.EmailField(max_length=50)
user_pass = models.CharField(max_length=30)
def __str__(self):
return "%s" % self.full_name
class CustomerDetail(models.Model):
phone_regex = RegexValidator(regex = r'^\d{10}$', message = "Invalid format! E.g. 4088385778")
date_regex = RegexValidator(regex = r'\d{2}[-/]\d{2}[-/]\d{2}', message = "Invalid format! E.g. 05/16/91")
address = models.CharField(max_length=100)
date_of_birth = models.CharField(validators = [date_regex], max_length = 10, blank = True)
company = models.CharField(max_length=30)
home_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
work_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE)
I added customer_id to Customer after I added the same in CustomerDetail as foreign key. Why do I still get this error after running migrate, even after I added unique=True to customer_id?
Error:
Rendering model states... DONE
Applying newuser.0003_auto_20160823_0128...Traceback (most recent call last):
File "/home/krag91/Documents/djangodev/virtualenv /lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv /lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: newuser_customer.customer_id
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/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute()
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 202, in handle
targets, plan, fake=fake, fake_initial=fake_initial
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 97, in migrate
state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 132, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 237, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/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/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards
field,
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 231, in add_field
self._remake_table(model, create_fields=[field])
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 199, in _remake_table
self.quote_name(model._meta.db_table),
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 112, in execute
cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: newuser_customer.customer_id
It seems like you are already having some objects as per old model definitions. By default django creates a field named as id to every model in database. It can be accesses by modelName.id.
In your case I guess what happened is that you are having some objects in database with customer.id as primary as primary key. So when you changed the models and applied migrations, existing objects are checked and another unique field is tried to added as a primary key. Here the workaround is to delete all the existing objects after removing the customer_id field and then try recreating the field and run migrations.
HTH