TL;DR - Using django-custom-user and django-registration-redux, I am having trouble setting up a postgres database even on a virgin instance. It complains of a non-existent relationship, and I don't see why or where. The detail of the question below is not long but includes some error snippets that are moderately long. Any pointers much appreciated.
Using django-custom-user, I've learned that I must first make a migration for custom_user before the remaining migrations will work. Fair enough. On a clean instance (just created a database and git clone'd the code), I type
python manage.py makemigrations custom_user
python manage.py makemigrations
python manage.py migrate
But... no, I'm missing custom_user_emailuser. I suspect this means a relationship from custom_user on key emailuser, but I still find myself stumped on where this comes from and so what to do about it. Any tips much appreciated.
╭╴ (user-model-74=) [virt]╶╮
╰ [T] django#beta11:django $ python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: admindocs, kernel, messages, staticfiles, blog
Apply all migrations: custom_user, sites, auth, sessions, contenttypes, registration, admin
Synchronizing apps without migrations:
Creating tables...
Creating table blog_blogentry
Creating table kernel_userprofile
Creating table kernel_trippending
Running deferred SQL...
Traceback (most recent call last):
File "/src/django/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
psycopg2.ProgrammingError: relation "custom_user_emailuser" does not exist
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 179, in handle
created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
File "/src/django/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps
cursor.execute(statement)
File "/src/django/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/src/django/venv/lib/python3.4/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/src/django/venv/lib/python3.4/site-packages/django/utils/six.py", line 658, in reraise
raise value.with_traceback(tb)
File "/src/django/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "custom_user_emailuser" does not exist
╭╴ (user-model-74=) [virt]╶╮
╰ 1,[T] django#beta11:django $
which I don't understand, even worse because the custom_user migration doesn't call for such a thing:
╭╴ (user-model-74=) [virt]╶╮
╰ [T] django#beta11:django $ more venv/lib/python3.4/site-packages/custom_user/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
]
operations = [
migrations.CreateModel(
name='EmailUser',
fields=[
('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_nam
e='ID')),
('password', models.CharField(verbose_name='password', max_length=128)),
('last_login', models.DateTimeField(null=True, blank=True, verbose_name='last login')),
('is_superuser', models.BooleanField(help_text='Designates that this user has all permiss
ions without explicitly assigning them.', verbose_name='superuser status', default=False)),
('email', models.EmailField(verbose_name='email address', unique=True, max_length=255, db
_index=True)),
('is_staff', models.BooleanField(help_text='Designates whether the user can log into this
admin site.', verbose_name='staff status', default=False)),
('is_active', models.BooleanField(help_text='Designates whether this user should be treat
ed as active. Unselect this instead of deleting accounts.', verbose_name='active', default=True)),
('date_joined', models.DateTimeField(verbose_name='date joined', default=django.utils.tim
ezone.now)),
('groups', models.ManyToManyField(related_name='user_set', to='auth.Group', help_text='Th
e groups this user belongs to. A user will get all permissions granted to each of their groups.', blank=T
rue, verbose_name='groups', related_query_name='user')),
('user_permissions', models.ManyToManyField(related_name='user_set', to='auth.Permission'
, help_text='Specific permissions for this user.', blank=True, verbose_name='user permissions', related_q
uery_name='user')),
],
options={
'abstract': False,
'verbose_name': 'user',
'swappable': 'AUTH_USER_MODEL',
'verbose_name_plural': 'users',
},
),
]
╭╴ (user-model-74=) [virt]╶╮
╰ [T] django#beta11:django $
It turns out that custom_user must be migrated before the rest of the world, but sites even before custom_user. So this solved our problem:
python manage.py migrate sites
python manage.py migrate custom_user
python manage.py migrate
Related
I am havnig troulble about migrating..I first tried
python manage.py migrate qablog
and didn't work. so I tried
python manage.py migrate qablog --fake-initial
and didn't work too.. so I googled again and some people were talking about changing the settings.py so I changed some things like changing USE_TZ to false ..
python manage.py makemigrations qablog
worked well though...can anyone help me with this? ..
python version: 3.4.4
mysql server version: 5.7
django version: 1.10.3
The error log is like below:
C:\inetpub\wwwroot\test>python manage.py migrate qablog --fake-initial
Operations to perform:
Apply all migrations: qablog
Running migrations:
Applying contenttypes.0001_initial... FAKED
Applying auth.0001_initial... OK
Applying qablog.0001_initial... OK
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
367, in execute_from_command_line
utility.execute()
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 294,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 345,
in execute
output = self.handle(*args, **options)
File "C:\Python34\lib\site-packages\django\core\management\commands\migrate.py
", line 224, in handle
self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps,
plan=plan,
File "C:\Python34\lib\site-packages\django\core\management\sql.py", line 53, i
n emit_post_migrate_signal
**kwargs
File "C:\Python34\lib\site-packages\django\dispatch\dispatcher.py", line 191,
in send
response = receiver(signal=self, sender=sender, **named)
File "C:\Python34\lib\site-packages\django\contrib\auth\management\__init__.py
", line 83, in create_permissions
Permission.objects.using(using).bulk_create(perms)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 452, in b
ulk_create
ids = self._batched_insert(objs_without_pk, fields, batch_size)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 1068, in
_batched_insert
self._insert(item, fields=fields, using=self.db)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 1045, in
_insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python34\lib\site-packages\django\db\models\sql\compiler.py", line 10
53, in execute_sql
for sql, params in self.as_sql():
File "C:\Python34\lib\site-packages\django\db\models\sql\compiler.py", line 10
38, in as_sql
result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
File "C:\Python34\lib\site-packages\mysql\connector\django\operations.py", lin
e 223, in bulk_insert_sql
return "VALUES " + ", ".join([items_sql] * num_values)
TypeError: can't multiply sequence by non-int of type 'tuple'
[manage.py]
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "swingqa.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
[models.py]
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
and for the migration file.. I looked inside the qablog > migrations folder and there are init and 0001_initial file.. init file is empty (it's just blank inside) and 0001_ initial file is like below
[0001_initial.py]
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-10 07:56
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('text', models.TextField()),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('published_date', models.DateTimeField(blank=True, null=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
I'd really appreciate for some help :-)
found a solution to this question by myself :-)
I don't really know the reason but
if you change operations.py file in this path below
C:\Python34\Lib\site-packages\mysql\connector\django
especially the part where def bulk_insert_sql function is,,from
def bulk_insert_sql(self, fields, num_values):
items_sql = "({0})".format(", ".join(["%s"] * len(fields)))
return "VALUES " + ", ".join([items_sql] * num_values)
to ...
def bulk_insert_sql(self, fields, placeholder_rows):
"""
Format the SQL for bulk insert
"""
placeholder_rows_sql = (", ".join(row) for row in placeholder_rows)
values_sql = ", ".join("(%s)" % sql for sql in placeholder_rows_sql)
return "VALUES " + values_sql
there will be no errors in doing python manage.py migrate qablog command.
Please help! I tried searching for an answer, but I think this issue is too specific to have a generalized enough solution.
It's very difficult for me to pin point when, exactly, it is that this error started. I've Attempted too many changes now to know when the site was last working. I'm very new to this. And entirely self-taught, at that. I can assure you, it will be apparent.
when attempting to migrate I receive this error:
when attempting to migrate I receive this error:
Apply all migrations: admin, auth, contenttypes, purchase_log, sessions
Running migrations:
Applying purchase_log.0009_auto_20161005_1524...Traceback (most recent call la
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
utility.execute()
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
self.execute(*args, **cmd_options)
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
output = self.handle(*args, **options)
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
fake_initial=fake_initial,
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_i
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
state = migration.apply(state, schema_editor)
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
operation.database_forwards(self.app_label, schema_editor, old_state, projec
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
field,
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
self._remake_table(model, create_fields=[field])
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
self.effective_default(field)
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
default = field.get_db_prep_save(default, self.connection)
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
prepared=False)
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
value = self.get_prep_value(value)
File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not
I'm going insane, and have no idea where to start! Please help!
edit: Here is the .models.py
from django.db import models
from django.contrib.auth.models import User
class Store(models.Model):
name = models.CharField(max_length=250)
owner = models.ForeignKey(User)
def __str__(self):
return self.name
class Product(models.Model):
type = models.CharField(max_length=250)
owner = models.ForeignKey(User)
def __str__(self):
return self.type
class Receipt(models.Model):
store = models.ForeignKey(Store)
date = models.DateField()
line_items = models.ManyToManyField(Product, through='ReceiptProduct')
owner = models.ForeignKey(User)
def __str__(self):
return self.store.name + ': ' + str(self.date)
class ReceiptProduct(models.Model):
receipt = models.ForeignKey(Receipt)
product = models.ForeignKey(Product)
price = models.FloatField()
sale = models.BooleanField()
description = models.CharField(max_length=500, null=True, blank=True)
owner = models.ForeignKey(User)
def __str__(self):
return self.product.type
edit: Here is migration 0009_auto_20161005_1524.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-10-05 19:24
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('purchase_log', '0008_receiptproduct_sale'),
]
operations = [
migrations.AddField(
model_name='product',
name='owner',
field=models.ForeignKey(default=django.contrib.auth.models.User, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='receipt',
name='owner',
field=models.ForeignKey(default=django.contrib.auth.models.User, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='receiptproduct',
name='owner',
field=models.ForeignKey(default=django.contrib.auth.models.User, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='store',
name='owner',
field=models.ForeignKey(default=django.contrib.auth.models.User, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
Problem solved, thanks to #MosesKoledoye.
I deleted the migrations folder inside the app that was causing the problem. And recreated it by running 'python manage.py makemigrations <appname>' I then migrated to the server, and everything was great.
Thank you, #MosesKoledoye
This does not answer the original question, but it may help others who end up here based on the title.
One of many ways to get this error message is to use get_or_create() and forget it actually returns a tuple, as in the following example.
foo = Foo.objects.get_or_create(some_attribute='something') # foo is actually a tuple...
Bar.objects.get_or_create(foo=foo) # this will raise the error
The second call to get_or_create() raises the error (at least in Django 2.2):
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Foo'
This message is not very helpful, in my opinion. Note that a similar (erroneous) call to Bar.objects.create(), instead of get_or_create(), does yield a very clear error message.
The solution in this case is simple:
foo, created = Foo.objects.get_or_create(...
In Django 1.9 using SQLite as the database backend, I am getting an error when trying to apply migrations after modifying a model to use multi-table inheritance instead of the OneToOneField relationship it was previously using.
Particularly, the problem seems to be due to including a ForeignKey('self') in the model.
models.py
Here is the app from which an initial migration is successfully made and applied:
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
account = models.OneToOneField(User)
parent = models.ForeignKey('self', null=True)
models.py (modified)
The app is then modified to inherit from the User model rather than linking to it:
from django.db import models
from django.contrib.auth.models import User
class Customer(User):
parent = models.ForeignKey('self', null=True)
At this point a ./manage.py makemigrations <app> succeeds but then applying the migration fails with:
Error
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/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 "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/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 "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 221, in add_field
self._remake_table(model, create_fields=[field])
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 181, in _remake_table
self.create_model(temp_model)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 250, in create_model
to_column = field.remote_field.model._meta.get_field(field.remote_field.field_name).column
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/models/options.py", line 582, in get_field
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: Customer has no field named 'id'
Again, the problem seems to only occur when using SQLite and including the self-referencing ForeignKey. I think it is occurring because SQLite can't ALTER columns resulting in Django rebuilding the table, but the self-referencing ForeignKey is causing the rebuild to look for the 'id' column which no longer exists in the new model.
I've tried manually adjusting the migration operations every which way and even adding a migrations.RunPython with apps.get_model() to use the historical version of the model. Nothing seems to work.
How can I adjust the following migration to avoid the error:
Migration
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-09-07 01:16
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('base', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='customer',
options={'verbose_name': 'user', 'verbose_name_plural': 'users'},
),
migrations.AlterModelManagers(
name='customer',
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.RemoveField(
model_name='customer',
name='account',
),
migrations.RemoveField(
model_name='customer',
name='id',
),
migrations.AddField(
model_name='customer',
name='user_ptr',
field=models.OneToOneField(auto_created=True, default=None, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]
And, yes, I know I'll ultimately need to break the migration into multiple phases and do a data migration to put something useful in the new user_ptr field.
Ok, it took me a while to work out: but basically, I don't think you can do this:
class Customer(User):
parent = models.ForeignKey('self', null=True)
Instead, it should be something more like (untested:)
class Customer(User):
parent = models.ForeignKey('admin.User', null=True)
If you want to make sure that data integrity is actually a Customer, you could put a pre-validate in save (or something, if you're using a save-pipeline of some kind)
If you include a data migration step to preserve that value as well, perhaps through using a temporary value to store it in (or dump and reinsert the objects).
Earlier I created two fields & migrated everything. after that I tried to add three fields title,about,birthdate into the model.
I created a model like this :
from __future__ import unicode_literals
from django.utils import timezone
from django.db import models
# Create your models here.
class APP1Model(models.Model):
name = models.CharField(max_length=120)
percentage = models.CharField(max_length=120)
title = models.CharField(max_length=100,default='Title')
birth_date = models.DateTimeField(blank=True, null=True)
about = models.TextField(max_length=100,null=True,default='About Yourself')
def __unicode__(self):
return self.name
But when I try to migrate in python shell, it is showing a validation error like this:
Operations to perform:
Apply all migrations: admin, contenttypes, auth, app1, sessions
Running migrations:
Applying app1.0005_auto_20160217_1346...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 221, in add_field
self._remake_table(model, create_fields=[field])
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 103, in _remake_table
self.effective_default(field)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 210, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 728, in get_db_prep_save
prepared=False)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1301, in get_db_prep_value
value = self.get_prep_value(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1296, in get_prep_value
return self.to_python(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1273, in to_python
params={'value': value},
django.core.exceptions.ValidationError: [u"'' value has an invalid date format. It must be in YYYY-MM-DD format."]
How to rectify this? I tried all solution i read here but it doesn't work?
I am using Django: 1.9.2
My migration File
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app1', '0004_auto_20160217_0427'),
]
operations = [
migrations.AddField(
model_name='app1model',
name='about',
field=models.TextField(default='About Yourself', max_length=100, null=True),
),
migrations.AddField(
model_name='app1model',
name='birth_date',
field=models.DateField(blank=True, default='', null=True),
),
migrations.AddField(
model_name='app1model',
name='title',
field=models.CharField(default='', max_length=100),
),
]
I went through the same problem some months back.I Just deleted the birthdate field changes in all the migration Files inside migration folder. Then I replaced the birthdate with this code:-
birthdate = models.DateTimeField(blank=True, null=True)
Then after applying migration ,it works fine...
It seems you have passed DateTimeField
birth_date = models.DateTimeField(blank=True, null=True)
in your APP1Model(model) and migration shows DateFields
models.DateField(blank=True, default='', null=True)
first correct your Model and don't pass default='' in DateField,
Use DateField instead of DatiTimeField for birthdate
then remove your migration file app1.0005_auto_20160217_1346
and run makemigrations and migrate your app it'll work fine.
Changing the DateField to DateTimeField is not a bad idea. Although, there is a DateField and a DateTimeField, which are different for some reasons.
This error happens when a default value is applied to DateField in models.py in the wrong format.
According to your terminal output, the error occurs in migration file 0005_auto_20160217_1346.py. You must find that migration file in 'app1/0005_auto_20160217_1346.py`, edit it and look for:
...
migrations.AddField(
model_name='app1model',
name='birth_date',
field=models.DateField(blank=True, default='<jamming-date>', null=True),
),
...
Now, you can see the DateField with the default attribute containing a <jamming-date> with format %d-%m-%Y, for example. Django needs a %Y-%m-%d format.
In order to solve this problem, delete the default attribute, save the file and make migrations again.
Just remove default=' ' in migrations file and run migrate .
Before:
migrations.AddField(
model_name='formd',
name='cash_payment_date',
field=models.DateField(blank=True, default='', help_text='Date of Cash Payment', null=True),
),
After:
migrations.AddField(
model_name='formd',
name='cash_payment_date',
field=models.DateField(blank=True, help_text='Date of Cash Payment', null=True),
),
Removed default=''
Ran makemigrations
I had this same error after trying to change the default property on a DateTime from blank '' (set in my initial migration file) to django.utils.timezone.now (in a later migration). You need to go back and edit your 0001_Initial.py file and change the default value to whatever you want it to be now. It seems like when applying migrations Django is referencing back to that initial file for validation and throwing the error, which can be a bit misleading, took me a few hours trying to sort out why... hopefully I save someone some time :)
Getting this error when running python manage.py migrate:
ValueError: Lookup failed for model referenced by field account.UserProfile.user: auth.User
Steps I did:
1. Created project and added new app:
$ django-admin.py startproject djdev
$ cd djdev
$ python manage.py startapp account
2. I added new app to INSTALLED_APPS in djdev/settings.py:
...
'django.contrib.staticfiles',
'account',
)
...
3. Created a new UserProfile model class in account/models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
"""
User Profile having one-to-one relations with User
"""
class Meta:
db_table = 'user_profile'
ordering = ['id']
user = models.OneToOneField(User, db_column='id_user', related_name='profile')
mobile_no = models.CharField('Mobile no.', db_column='contact_no_home', max_length=16, blank=True, null=True)
address_line_1 = models.CharField('Address Line 1', db_column='contact_address_line_1_home', max_length=140, blank=True, null=True)
address_line_2 = models.CharField('Address Line 2', db_column='contact_address_line_2_home', max_length=140, blank=True, null=True)
office_mobile_no = models.CharField('Mobile no.', db_column='contact_no_office', max_length=16, blank=True, null=True)
office_address_line_1 = models.CharField('Address Line 1', db_column='contact_address_line_1_office', max_length=140, blank=True, null=True)
office_address_line_2 = models.CharField('Address Line 2', db_column='contact_address_line_2_office', max_length=140, blank=True, null=True)
about = models.TextField('About me', blank=True, null=True)
note = models.CharField('Note', max_length=255, blank=True, null=True)
def __unicode__(self):
return self.user.name
4. Started migrating:
$ python manage.py makemigrations account
$ python manage.py migrate
After executing last command python manage.py migrate I'm getting this error:
Operations to perform:
Synchronize unmigrated apps: (none)
Apply all migrations: admin, contenttypes, account, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
Applying account.0001_initial...Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/vinay/python_webapps/django-trunk/django/core/management/__init__.py", line 427, in execute_from_command_line
utility.execute()
File "/home/vinay/python_webapps/django-trunk/django/core/management/__init__.py", line 419, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/vinay/python_webapps/django-trunk/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/vinay/python_webapps/django-trunk/django/core/management/base.py", line 337, in execute
output = self.handle(*args, **options)
File "/home/vinay/python_webapps/django-trunk/django/core/management/commands/migrate.py", line 146, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/home/vinay/python_webapps/django-trunk/django/db/migrations/executor.py", line 62, in migrate
self.apply_migration(migration, fake=fake)
File "/home/vinay/python_webapps/django-trunk/django/db/migrations/executor.py", line 90, in apply_migration
if self.detect_soft_applied(migration):
File "/home/vinay/python_webapps/django-trunk/django/db/migrations/executor.py", line 134, in detect_soft_applied
apps = project_state.render()
File "/home/vinay/python_webapps/django-trunk/django/db/migrations/state.py", line 83, in render
model=lookup_model
ValueError: Lookup failed for model referenced by field account.UserProfile.user: auth.User
NOTE: Django Version I'm using: 1.8.dev20140507130401
This is already fixed in the master branch.
Fixed in commits:
https://code.djangoproject.com/changeset/8f6dff372b174e772920de6d82bd085f1a74eaf2
https://code.djangoproject.com/changeset/35c2a14a49ac3cb25dcff818b280bf0b4c290287
You can install it until a proper release is built:
pip install https://github.com/django/django/zipball/master
Test:
models.py
from django.db import models
from django.contrib.auth.models import User
class Test(models.Model):
user = models.OneToOneField(User)
Results
[__env] $ ./manage.py makemigrations
Migrations for 'data':
0001_initial.py:
- Create model Test
[__env] $ ./manage.py migrate
Operations to perform:
Synchronize unmigrated apps: admin, contenttypes, auth, sessions
(... ommited ...)
Running migrations:
Applying data.0001_initial... OK
I read the comment above as suggesting adding only the last line in the dependencies list (('contenttypes',' __first__')), but I had to add the last two to correct the problem. This might be obvious to those with a better understanding of the makemigrations tool in Django, but I am new to it and it was not to me.
My last migrations file dependencies list that was originally giving the same error...
dependencies = [
('myapp', '0006_auto_20150209_0324'),
(b'auth', b'__first__'),
(b'contenttypes', b'__first__'),
]
I've found another solution that also work fine.
See the solution of by rockallite.wulf#
https://code.djangoproject.com/ticket/22488
Just add the corresponding dependency in the migration file, like this:
dependencies = [
(b'advperm', b'0001_initial'),
(b'auth', b'__first__'),
(b'contenttypes', b'__first__'), # Add this line
]