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.
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.
I added a custom extension to djangos User model and now I'm getting this error on my localhost url:
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column users_account.birthday does not exist
LINE 1: ... "users_account"."id", "users_account"."user_id", "users_acc...
^
Furthermore, when I tried to migrate my changes I got this error in the terminal:
Operations to perform:
Apply all migrations: admin, auth, chaburah, contenttypes, sessions, taggit, users
Running migrations:
Applying users.0002_alter_account_birthday...Traceback (most recent call last):
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedColumn: column "birthday" does not exist
LINE 1: ..._account" ALTER COLUMN "birthday" TYPE date USING "birthday"...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/almoni/Desktop/Code/my_chaburah/manage.py", line 22, in <module>
main()
File "/Users/almoni/Desktop/Code/my_chaburah/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 290, in handle
post_migrate_state = executor.migrate(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/executor.py", line 131, in migrate
state = self._migrate_all_forwards(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards
state = self.apply_migration(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/executor.py", line 248, in apply_migration
state = migration.apply(state, schema_editor)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/migration.py", line 131, in apply
operation.database_forwards(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 235, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 747, in alter_field
self._alter_field(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/postgresql/schema.py", line 231, in _alter_field
super()._alter_field(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 963, in _alter_field
self.execute(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 192, in execute
cursor.execute(sql, params)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 103, in execute
return super().execute(sql, params)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "birthday" does not exist
LINE 1: ..._account" ALTER COLUMN "birthday" TYPE date USING "birthday"...
It only appears when I try to either edit an existing User or create a new one.
models.py:
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthday = models.DateTimeField(blank=True, null=True)
def __str__(self):
return self.user
admin.py:
class AccountInline(admin.StackedInline):
model = Account
can_delete = False
verbose_name_plural = 'Accounts'
class CustomUserAdmin(UserAdmin):
inlines = (AccountInline,)
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
My original guess was the error was due to the fact that my existing Users have no birthday but that doesn't explain why I can't create a new User. Which makes me think I am unaware of what the actual problem is.
I'm newish to django/SQl so I don't really understand the error itself.
You forgot about:
python manage.py makemigrations
# and/or
python manage.py migrate
If error still occurs - delete the database, create new and then run above commands. If got still same error - delete the database and all migration files and then run the commands.
PS You probably want DateField not DateTimeField for birthday storage :)
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)
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
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.