Does get_prep_value() have to handle value = None? - django

I'm trying to create a custom field. It's based on postgres.JSONField.
class CardiosField(JSONField):
"""Field representing a models.Cardios object"""
def from_db_value(self, value, expression, connection):
if value is None:
return value
return parse_cardios(value)
def to_python(self, value):
if isinstance(value, models.Cardios):
return value
if value is None:
return value
return parse_cardios(value)
def get_prep_value(self, value):
cardios_pre_json = [serie_object.pre_json() for serie_object in value.series]
return json.dumps(cardios_pre_json)
I've created a model that has this field:
class Workout(models.Model):
datetime = models.DateTimeField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
lifts = fields.LiftsField(null=True)
cardios = fields.CardiosField(null=True)
def __str__(self):
return str(self.datetime)+" "+self.user.email
__repr__ = __str__
I make migrations without a problem, but when I try to migrate, this happens:
(workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, workoutcal
Running migrations:
Applying workoutcal.0003_auto_20171231_2308...Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards
field,
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 415, in add_field
definition, params = self.column_sql(model, field, include_default=True)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 155, in column_sql
default_value = self.effective_default(field)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 229, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save
prepared=False)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 762, in get_db_prep_value
value = self.get_prep_value(value)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/workoutcal/fields.py", line 52, in get_prep_value
cardios_pre_json = [serie_object.pre_json() for serie_object in value.series]
AttributeError: 'NoneType' object has no attribute 'series'
Does get_prep_value() have to deal with None? I've read the docs and this doesn't seem to be the case, at least not in their code example. Could anyone explain what's going wrong here?

Thank you #solarissmoke for this solution:
get_prep_value has to deal with None since I've set null=True for the field:
def get_prep_value(self, value):
if not value:
return value
cardios_pre_json = [serie_object.pre_json() for serie_object in value.series]
return json.dumps(cardios_pre_json)

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)

TypeError: expected string or bytes-like object although datetime field not used Django

I'm trying to migrate my datas, but django returns me TypeError: expected string or bytes-like object error, although I just tried using datetime once, then deleted it, but still it returns an error. Here are my codes:
models.py
class Applicant(models.Model):
name = models.CharField(max_length=20)
surname = models.CharField(max_length=30)
phone = models.CharField(max_length=15)
email = models.EmailField(max_length=40)
motivation_letter = models.TextField(max_length=200)
is_accepted = models.BooleanField(default=False)
photo = models.FileField(upload_to='static/applicant_photos')
def __str__(self):
return self.name
an error:
Operations to perform:
Apply all migrations: admin, auth, ccapp, contenttypes, sessions
Running migrations:
Applying ccapp.0003_applicant_birth_date...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 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle
fake_initial=fake_initial,
File "/Library/Frameworks/Python.framework/Versions/3.7/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 "/Library/Frameworks/Python.framework/Versions/3.7/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 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards
field,
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/schema.py", line 327, in add_field
self._remake_table(model, create_field=field)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/schema.py", line 188, in _remake_table
self.effective_default(create_field)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 233, in effective_default
return field.get_db_prep_save(self._effective_default(field), self.connection)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 789, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1431, in get_db_prep_value
value = self.get_prep_value(value)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1410, in get_prep_value
value = super().get_prep_value(value)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1270, in get_prep_value
return self.to_python(value)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1371, in to_python
parsed = parse_datetime(value)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/dateparse.py", line 106, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object

StreamField – TypeError: 'bool' object is not iterable

Build: Wagtail CMS(1.13.1) with Django(1.11) in python3.6.
I am trying to create a pretty basic Streamfield block(CardBlock), but keep getting a type error. It is very similar to the examples in documentation, but I can not get it to work...
class CardBlock(StructBlock):
image = ImageChooserBlock()
heading = CharBlock(classname="full title")
caption = RichTextBlock()
class Meta:
icon = 'image'
class HomePage(Page):
intro = RichTextField(blank=True)
showcase_title = RichTextField(blank=True)
card = StreamField([('card', CardBlock())], default=True)
content_panels = Page.content_panels + [
FieldPanel('intro', classname="full"),
MultiFieldPanel([
FieldPanel('showcase_title'),
StreamFieldPanel('card'),
]),
]
django is trying to "get_db_prep_value()". So, Wagtail tries to "get_prep_value()", for all children(streamchild instances) in value, as shown below. wagtail/wagtailcore/blocks/stream_block.py (line 257):
def get_prep_value(self, value):
if value is None:
# treat None as identical to an empty stream
return []
return [
{
'type': child.block.name,
'value': child.block.get_prep_value(child.value),
# assign a new ID on save if it didn't have one already
'id': child.id or str(uuid.uuid4()),
}
for child in value # child is a StreamChild instance
]
I am uncertain as to what this value is.
What in my block classes needs to be changed to correct this value variable?
Edit1- Full Error:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, home, sessions,
taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms,
wagtailimages, wagtailredirects, wagtailsearch, wagtailusers
Running migrations:
Applying home.0006_auto_20180220_1223...Traceback (most recent call last):
File "manage.py", line 12, in <module>
execute_from_command_line(sys.argv)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/core/management/__init__.py", line 363, in
execute_from_command_line
utility.execute()
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake,
fake_initial=fake_initial)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake,
fake_initial=fake_initial)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state,
project_state)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/db/migrations/operations/fields.py", line 86, in
database_forwards
field,
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/db/backends/sqlite3/schema.py", line 238, in add_field
self._remake_table(model, create_field=field)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/db/backends/sqlite3/schema.py", line 113, in _remake_table
self.effective_default(create_field)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/db/backends/base/schema.py", line 228, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/db/models/fields/__init__.py", line 766, in get_db_prep_save
prepared=False)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/django/db/models/fields/__init__.py", line 758, in get_db_prep_value
value = self.get_prep_value(value)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/wagtail/wagtailcore/fields.py", line 109, in get_prep_value
return json.dumps(self.stream_block.get_prep_value(value),
cls=DjangoJSONEncoder)
File "//anaconda/envs/WagtailCMS/lib/python3.6/site-
packages/wagtail/wagtailcore/blocks/stream_block.py", line 257, in
get_prep_value
for child in value # child is a StreamChild instance
TypeError: 'bool' object is not iterable
The error is on the line:
card = StreamField([('card', CardBlock())], default=True)
The default parameter is used to specify a default/initial value for the field; in this case, you're setting that value to True, which doesn't make sense as a StreamField value. (A StreamField is a list of blocks, so it's trying and failing to loop over the value True to populate the stream...)
Perhaps you meant blank=False instead?

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

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

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