Django ValueError: Cannot serialize: <User: username> - django

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.

Related

ValueError: Field 'id' expected a number but got 'DEFAULT VALUE'

When I try to execute python manage.py migrate I get this error: ValueError: Field 'id' expected a number but got 'DEFAULT VALUE'.What could be wrong with my code.Any help pleaseThanks in advance.
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1772, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'DEFAULT VALUE'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle
fake_initial=fake_initial,
File "/home/risper/django_projects/env01/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 "/home/risper/django_projects/env01/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 "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/risper/django_projects/env01/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 "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards
field,
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 328, in add_field
self._remake_table(model, create_field=field)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 189, in _remake_table
self.effective_default(create_field)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 303, in effective_default
return field.get_db_prep_save(self._effective_default(field), self.connection)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/related.py", line 939, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 821, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2365, in get_db_prep_value
value = self.get_prep_value(value)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1776, in get_prep_value
) from e
ValueError: Field 'id' expected a number but got 'DEFAULT VALUE'.
Here is my models py file where I have defined my models:
from django.db import models
# Create your models here.
class ImageModel(models.Model):
imagefile=models.ImageField(upload_to='images', null=True, verbose_name="")
def __str__(self):
return str(self.imagefile)
class Diseases(models.Model):
disease_name=models.CharField(max_length=100)
description=models.CharField(max_length=100)
def __str__(self):
return self.disease_name
class Pestisides(models.Model):
pestiside_name=models.CharField(max_length=100)
directions=models.CharField(max_length=100)
price=models.CharField(max_length=100)
#test_location=
#time
disease= models.ManyToManyField(Disease)
def __str__(self):
return self.pestiside_name
class Predictions(models.Model):
#user= models.ForeignKey(User, on_delete=models.CASCADE,null=True)
disease = models.ForeignKey(Diseases,on_delete=models.CASCADE)
Here is my admin py file where I have registered my models:
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(ImageModel)
admin.site.register(Diseases)
admin.site.register(Pestisides)
admin.site.register(Predictions)
Firstly disease = models.ManyToManyField(Diseases) correct model Name. Then delete all your migrations and then type manage.py makemigrations and migrate commands. I hope it will work
class Pestisides(models.Model):
pestiside_name = models.CharField(max_length=100)
directions = models.CharField(max_length=100)
price = models.CharField(max_length=100)
# test_location=
# time
disease = models.ManyToManyField(Diseases)

AttributeError: type object 'Product' has no attribute '_parler_meta' - DJANGO

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.

django - UNIQUE CONSTRAINED FAILED 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

Fail Load Data Fixtures Django - integer out of range

I'm developing app using Django and Postgre.
Basically, I create new model on my app.
from django.db import models
from manager.models.state import State
from django.contrib.auth.models import User
class Address (models.Model):
address_id = models.AutoField(primary_key=True)
address_name = models.CharField(max_length=500)
address_city = models.CharField(max_length=250)
address_phone = models.IntegerField()
address_postcode = models.CharField(max_length=10, default = 0)
state = models.ForeignKey(State, null=True, blank=True, default = None)
user = models.ForeignKey(User, null=True, blank=True, default = None)
def __unicode__(self):
return self.address_id
#classmethod
def get_list(cls):
return list(cls.objects.values())
After that I run makemigrations and migrate commandline. All of the models are created on database normally.
I successfully load data from other json file (fixtures).
When I tried to loaddata address.json on Address table, I got this error.
The Error Message:
django.db.utils.DataError: Problem installing fixture '/Users/eeldwin/Documents/Django/fbt/manager/fixtures/address.json': Could not load manager.Address(pk=1): integer out of range
The Traceback:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_from_command_line(sys.argv)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django /core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 61, in handle
self.loaddata(fixture_labels)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 91, in loaddata
self.load_label(fixture_label)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 148, in load_label
obj.save(using=self.using)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/serializers/base.py", line 173, in save
models.Model.save_base(self.object, using=using, raw=True)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/base.py", line 617, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/base.py", line 679, in _save_table
forced_update)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/base.py", line 723, in _do_update
return filtered._update(values) > 0
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/query.py", line 600, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1004, in execute_sql
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/backends/utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.DataError: Problem installing fixture '/Users/eeldwin/Documents/Django/fbt/manager/fixtures/address.json': Could not load manager.Address(pk=1): integer out of range
Here's my fixtures
[{
"model": "manager.address",
"pk": 1,
"fields": {
"address_id": "1",
"address_name": "Jalan Muara Mas Timur 242",
"address_city": "Semarang",
"address_phone": "087832270893",
"address_postcode": "3122",
"state": "1"
}}]
However, when I inserted data to database manually, it will run perfectly. Any ideas what's happened here? Thanks.
You store address_phone as IntegerField. Its max value is 2147483647 (https://docs.djangoproject.com/en/1.7/ref/models/fields/#integerfield).
But in your fixtures you try to add 087832270893 as address_phone, that why you receive integer out of range error.

Django Model SyncDB fail on the choices attribute due to a DB error

Here is a little error I get when trying to use syncdb on my django project.
Error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 219, in execute
self.validate()
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 146, in get_app_errors
self._populate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/opt/admin-site/adminsite/cfadmin/models.py", line 111, in <module>
class RequestLog(models.Model):
File "/opt/admin-site/adminsite/cfadmin/models.py", line 117, in RequestLog
profile = models.PositiveIntegerField(null=True,blank=True, choices=get_profiles()) # It cannot be a foreign key this is not on the same DB
File "/opt/admin-site/adminsite/cfadmin/models.py", line 107, in get_profiles
cache.set('profiles_choices', profiles_choices, 3600)
File "/usr/local/lib/python2.6/dist-packages/django/core/cache/backends/locmem.py", line 83, in set
self._set(key, pickle.dumps(value), timeout)
File "/usr/lib/python2.6/copy_reg.py", line 84, in _reduce_ex
dict = getstate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 61, in __getstate__
len(self)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 81, in __len__
self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 947, in iterator
for row in self.query.get_compiler(self.db).results_iter():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 672, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 727, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute
return self.cursor.execute(query, args)
django.db.utils.DatabaseError: relation "cfadmin_profile" does not exist
LINE 1: ...dmin_profile"."id", "cfadmin_profile"."name" FROM "cfadmin_p...
The models:
class Profile(models.Model):
name = models.CharField(max_length=256)
categories = models.ManyToManyField(Category)
def __unicode__(self):
return self.name
class Meta():
ordering = ["name"]
def get_profiles():
profiles_choices = cache.get('profiles_choices')
if profiles_choices == None:
try:
profiles_choices = Profile.objects.values_list('id','name')
cache.set('profiles_choices', profiles_choices, 3600)
except:
logging.info("Failed to retrieve the profile choices.")
pass
return profiles_choices
class Log(models.Model):
domain = models.CharField(max_length=512)
profile = models.PositiveIntegerField(null=True,blank=True, choices=get_profiles()) # this is where I get the error on Syncdb
def __unicode__(self):
return self.domain
class Meta():
ordering = ["domain"]
So if I am syncing a new project I will get the error that I mentioned earlier.
If I remove the call to my function get_profiles() in the model choices, it will synchronize with no error.
But I don't understand why I'm still getting the error even do I put a try catch within the function.
So in case of an error I would expect that it continues but instead it's completely aborting the syncdb.
Is there anyway to achieve what I'm trying to without removing the function and the put it back?
Thank you!
From the django doc " ... if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever."
So you are probably better of changing your profile field in the Log model:
profile = models.ForeignKey(Profile, null=True,blank=True)
This is not the way to get choices for a model. Even if you fix your circular dependency problem, you will still have the issue that the get_choices() function will be called when the server process starts, and won't change in the meantime. Unlike default, I don't believe choices can be a callable.