ValueError: badly formed hexadecimal UUID string - django

In my system I'm trying to auto generate a unique random string for each users to be passed later on in the URL as the reference to that account and I recently read about the UUID in django models. And this is how my model looks like:
class User(AbstractBaseUser, PermissionsMixin):
card_number = models.CharField(max_length=20, unique=True)
first_name = models.CharField(max_length=150)
middle_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
address = models.CharField(max_length=200)
account_code = models.UUIDField(max_length=200, default=uuid.uuid4(), editable=False)
And I ran into an error when start creating superuser in the terminal:
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\ViajeroProject\viaje\manage.py", line 22, in <module>
main()
File "C:\Users\User\PycharmProjects\ViajeroProject\viaje\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\base.py", line 371, in execute
output = self.handle(*args, **options)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 113, in handle
error_msg = self._validate_username(username, verbose_field_name, database)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 234, in _validate_username
self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\base_user.py", line 45, in get_by_natural_key
return self.get(**{self.model.USERNAME_FIELD: username})
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 425, in get
num = len(clone)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 269, in __len__
self._fetch_all()
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 70, in __iter__
for row in compiler.results_iter(results):
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1100, in apply_converters
value = converter(value, expression, connection)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\backends\sqlite3\operations.py", line 318, in convert_uuidfield_value
value = uuid.UUID(value)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\uuid.py", line 177, in __init__
raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string
How should I address this or is this practice not advisable where I auto generate a unique random string as reference for the user in the URL? Note that users still have their PKs which different from the account_code.
Thank you!

You need to import the module and use default=uuid.uuid4 instead of default=uuid.uuid4()

Related

Django ValueError: Cannot serialize: <User: username>

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.

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)

Django: Trying to make Users migration with a self-referential default value

I'm trying to set a default value on a field I added to my User model, but I'm having to do a lot of acrobativs to make it work.
I want to add an 'identifier' SlugField with a default value defined in a function, like so:
def create_identifier():
while True:
identifier = ''.join(random.SystemRandom().choice('23456789BCDFGHJKMNPQRSTVWXYZ') for _ in range(15))
if not User.objects.filter(identifier=identifier).exists():
return identifier
class User(AbstractUser):
identifier = models.SlugField(default=create_identifier, max_length=16)
def __str__(self):
return self.username
This exact scenario works fine on a different (not User) nodel class, but when I try to run migrations with this code for User, I get:
Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute
self.check()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks
issues.extend(super()._run_checks(**kwargs))
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/contrib/auth/checks.py", line 74, in check_user_model
if isinstance(cls().is_anonymous, MethodType):
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/base.py", line 469, in __init__
val = field.get_default()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 775, in get_default
return self._get_default()
File "/home/myprojectname/myprojectname/myprojectname/users/models.py", line 34, in create_identifier
if not User.objects.filter(identifier=identifier).exists():
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/query.py", line 715, in exists
return self.query.has_results(using=self.db)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/query.py", line 509, in has_results
return compiler.has_results()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1037, in has_results
return bool(self.execute_sql(SINGLE))
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1068, in execute_sql
cursor.execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "users_user" does not exist
LINE 1: SELECT (1) AS "a" FROM "users_user" WHERE "users_user"."iden...
I have to manually modify the migrations as such:
migrations.CreateModel(
name='User',
fields=[
...
('identifier', models.SlugField(default='', max_length=16)),
...
),
migrations.AlterField(
model_name='user',
name='identifier',
field=models.SlugField(default=myprojectname.users.models.create_identifier, max_length=16),
),
And then if I initially set default='' in the models.py and run migrations it works, and I can change back to default=create_identifier after the fact.
class User(AbstractUser):
identifier = models.SlugField(default='', max_length=16)
def __str__(self):
return self.username
Is there any way I can make this work without having to go through these measures?
Edit: Would I be better off just leaving blank=True, null=True and overriding the model's save() method to change the value if the field is blank or null?
I seem to have solved the issue by modifying create_identifier to the following:
def create_identifier():
while True:
identifier = ''.join(random.SystemRandom().choice('23456789BCDFGHJKMNPQRSTVWXYZ') for _ in range(15))
try:
present = User.objects.first()
except:
present = None
if present:
if not User.objects.filter(identifier=identifier).exists():
return identifier
else:
return identifier

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.