Changed Django model attribute and now getting error for it - python

I had a model with a DateField that worked just fine. I wanted to change it from a DateField to a CharField.
Before:
class NWEAScore(models.Model):
test_date = models.DateField(default=date.today, verbose_name='Test Date')
After:
class NWEAScore(models.Model):
year = models.CharField(max_length=50, choices=YEAR_CHOICES, default=SIXTEEN)
season = models.CharField(max_length=50, choices=SESSION_CHOICES, default=FALL)
Not sure what went wrong but now I'm getting an error.
Making migrations is no problem. I make them and then upload them to my server, then when I migrate, I get an error.
The Error I get when I try to apply my migrations:
(venv) alex#newton:~/newton$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, amc, auth, brain, contenttypes, ixl, nwea, sessions
Running migrations:
Rendering model states... DONE
Applying brain.0021_auto_20160927_0038... OK
Applying nwea.0011_auto_20160927_0038...Traceback (most recent call last):
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/models/options.py", line 612, in get_field
return self.fields_map[field_name]
KeyError: 'test_date'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 202, in handle
targets, plan, fake=fake, fake_initial=fake_initial
File "/home/alex/newton/venv/lib/python3.4/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/alex/newton/venv/lib/python3.4/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/alex/newton/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 237, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/alex/newton/venv/lib/python3.4/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/alex/newton/venv/lib/python3.4/site-packages/django/db/migrations/operations/models.py", line 525, in database_forwards
getattr(new_model._meta, self.option_name, set()),
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 329, in alter_unique_together
self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique)
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 352, in _delete_composed_index
columns = [model._meta.get_field(field).column for field in fields]
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 352, in <listcomp>
columns = [model._meta.get_field(field).column for field in fields]
File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/models/options.py", line 614, in get_field
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: NWEAScore has no field named 'test_date'
I went through and deleted all my instances from all my models, just incase a remaining "NWEAScore" Instance with a test_date was throwing the error.
I searched through my entire project for the term "test_date", trying to delete every instance, and the only remaining instances are in old migrations. Should I go back and delete those? Could that be throwing that off? I'm not too clear on how to wipe migrations and make new ones if that's it.
I gave it a shot for a few days, if anyone has suggestions thanks in advance!

Go to the migrations folder of your app and delete all files, except __init__.py. Then run the command:
python manage.py makemigrations
to make new migrations with the updated fields

Related

Django Misapplying Migrations

I am not sure whether I am doing something wrong or it is a problem with one of the pieces I am using for the project.
Basically, I added a field to a model and am trying to make a migration.
Here is the model. The field is the poster one.
class Video(models.Model):
title=models.CharField(max_length=500)
description=models.TextField(default="")
creation_date=models.DateTimeField(default=timezone.now)
videofile=models.FileField(upload_to='videos/', null=True, verbose_name="")
poster=models.ImageField(upload_to='video/thumbnails', null=True, verbose_name="")
tags = TaggableManager()
actions = ['delete']
def __str__(self):
return self.title + ": " + str(self.videofile)
...
That is the only thing that changed in the model. Let's make the migrations.
(app-web) selfishman#user-desktop:~/sites/app-web/app$ python manage.py makemigrations
Migrations for 'video_uploader':
video_uploader/migrations/0007_video_poster.py
- Add field poster to video
So far, so good. Let's try to apply the migration.
(app-web) user#user-desktop:~/sites/app-web/app$ python manage.py migrate video_uploader
Operations to perform:
Apply all migrations: video_uploader
Running migrations:
Applying video_uploader.0002_video_creation_date...Traceback (most recent call last):
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.DuplicateColumn: column "creation_date" of relation "video_uploader_video" already exists
There rest of the backtrace:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 20, in <module>
execute_from_command_line(sys.argv)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/commands/migrate.py", line 203, in handle
fake_initial=fake_initial,
File "/home/user/miniconda3/envs/app-web/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 "/home/user/miniconda3/envs/app-web/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 "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/migrations/
executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/user/miniconda3/envs/app-web/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 "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/migrations/
operations/fields.py", line 84, in database_forwards
field,
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ba
se/schema.py", line 435, in add_field
self.execute(sql, params)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ba
se/schema.py", line 133, in execute
cursor.execute(sql, params)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 100, in execute
return super().execute(sql, params)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/utils.py",
line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "creation_date" of relation "video_uploader_video" already exists
This is the migration that was created:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('video_uploader', '0006_video_description'),
]
operations = [
migrations.AddField(
model_name='video',
name='poster',
field=models.ImageField(null=True, upload_to='video/thumbnails', verbose_name=''),
),
]
Could someone tell me what is going on here? I am using Postgres 12. When I run tests, and an (SQLite) DB is created from scratch, there is no such error.
Any help is appreciated.
P.S. We have seen quite a few inconsistencies when it comes to Django migrations and Postgres/Psycopg2. Not sure if something is up with the config or versions/dependencies.
You created a new migration and it was named
0007_video_poster
However when you run the migrate it is running
0002_video_creation_date
And this is trying to create a new column named creation_date however that's already there.
You are getting inconsistent results because django thinks the previous migrations were not applied and therefore it is trying to apply them.
The easiest way would be to flush the database (make sure you first export any data you might need) using
python manage.py flush
This would reset the database and then you can run the migrations normally and it should work fine.
Otherwise if you want to execute the migration you just created i.e. 0007_video_poster
You can run this
python manage.py migrate video_uploader 0007_video_poster

timezone() missing required argument 'offset' (pos 1) in models.py while trying to migrate, what is the reason?

while making a blog, my models.py:
from django.db import models
class Post(models.Model):
title=models.CharField(max_length=200,blank=True)
author=models.ForeignKey('auth.user',on_delete=models.CASCADE,)
image=models.ImageField(upload_to='media/',blank=True)
content=models.CharField(max_length=1000,blank=True)
date=models.DateTimeField(auto_now_add=False, editable=False)
tag=models.CharField(max_length=100,blank=True)
slug=models.CharField(max_length=200,blank=True)
def __str__(self):
return self.title
when i run python manage.py makemigrations, datefield is created in database:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0013_auto_20191124_1448'),
]
operations = [
migrations.AlterField(
model_name='post',
name='date',
field=models.DateTimeField(editable=False),
),
]
but when i try to run python manage.py migrate, it shows the following error:
(Django-k7xSBAPV) C:\Myfiles\python\Django\myblog\blog_project>python manage.py
makemigrations
No changes detected
(Django-k7xSBAPV) C:\.....\blog_project>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
Applying blog.0004_post_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 "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\core\management\__init__.py", line 381, in
execute_from_command_line
utility.execute()
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\core\management\base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\core\management\base.py", line 364, in execute
output = self.handle(*args, **options)
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\core\management\commands\migrate.py", line 234, in handle
fake_initial=fake_initial,
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\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 "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\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 "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\db\migrations\executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\db\migrations\migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state,
project_state)
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\db\migrations\operations\fields.py", line 112, in database_forwards field,
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\db\backends\sqlite3\schema.py", line 327, in add_field
self._remake_table(model, create_field=field)
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\db\backends\sqlite3\schema.py", line 188, in _reremake_table
self.effective_default(create_field)
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\db\backends\base\schema.py", line 233, in effectctive_default
return field.get_db_prep_save(self._effective_default(field), self.connection)
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\db\backends\base\schema.py", line 212, in _effecective_default
default = field.get_default()
File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site-
packages\django\db\models\fields\__init__.py", line 801, in get_t_default
return self._get_default()
TypeError: timezone() missing required argument 'offset' (pos 1)
but without date in models.py, everything was working fine. i tried to use dafault=timezone.now() along with from django.utils.timezone import * but it's showing different warning.
please give me some suggestions. i am doing this in django2.2.
i think i solved the problem. i am sharing it if anyone wish to look through.... and i have polished the code...
from django.db import models
from django.utils import timezone
class Post(models.Model):
title=models.CharField(max_length=200)
author=models.ForeignKey(
'auth.User',on_delete=models.CASCADE,)
image=models.ImageField(upload_to='media/',blank=True)
content=models.CharField(max_length=1000)
date=models.DateTimeField(default=timezone.now)
tag=models.CharField(max_length=100)
slug=models.CharField(max_length=200)
def __str__(self):
return self.title
def publish_time(self):
publication=timezone.now()
self.save()
My main issue was i forget to migrate when i first created the app. i am not sure this is the main reason or not. but it worked smoothly.besides i have decided to use ckeditor, but it poses another problem which it just accepts picture from the link. that's why i prefer more ImageField....
any way this model.py file ran at first attempt while starting a clean app.
thanx again

django datetime declaration error

I added the following code in models.py :
class Conference(models.Model):
conf_name = models.CharField(max_length=250)
location = models.CharField(max_length=500)
note = models.TextField(max_length=500)
note2 = models.TextField(max_length=500)
date_from = models.DateField()
date_to = models.DateField()
time_from = models.TimeField(default='HH:MM:ss')
time_to = models.TimeField(default='HH:MM:ss')
After that I ran migration commands and I got the following traceback :
WARNINGS:
?: (mysql.W002) MySQL Strict Mode is not set for database connection 'appadmin'
HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.11/ref/databases/#mysql-sql-mode
?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.11/ref/databases/#mysql-sql-mode
?: (urls.W005) URL namespace 'dev_app' isn't unique. You may not be able to reverse all URLs in this namespace
Operations to perform:
Apply all migrations: admin, auth, contenttypes, dev_app, sessions
Running migrations:
Applying dev_app.0016_auto_20180112_0630...Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/usr/lib/python2.7/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 "/usr/lib/python2.7/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 "/usr/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 86, in database_forwards
field,
File "/usr/lib/python2.7/site-packages/django/db/backends/mysql/schema.py", line 48, in add_field
super(DatabaseSchemaEditor, self).add_field(model, field)
File "/usr/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 414, in add_field
definition, params = self.column_sql(model, field, include_default=True)
File "/usr/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 154, in column_sql
default_value = self.effective_default(field)
File "/usr/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 228, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 766, in get_db_prep_save
prepared=False)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 2277, in get_db_prep_value
value = self.get_prep_value(value)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 2272, in get_prep_value
return self.to_python(value)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 2259, in to_python
params={'value': value},
django.core.exceptions.ValidationError: [u"'null' value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format."]
Even after I reverted the code in models.py, the traceback has persisted.
I need help understanding the traceback.
The code was working properly before the changes in models were applied. The models migrated properly.
I also flushed the database and tried to migrate again, it gave the same result.
Your time_from and time_to default is wrong. You should provide a default value not a format. If your model is new remove the migration file (I think dev_app.0016_auto_20180112_0630) change default values and run manage.py makemigrations again.

Django migrations mixed up with 'PROTECT' and 'CASCADE'

I am stuck with migrations in django. I have two really basic models that will not migrate:
from django.db import models
# Create your models here.
class Instanz(models.Model):
type = models.CharField(max_length=30)
angelegt_am = models.DateField(auto_now_add=True)
class Person(models.Model):
instanz_fk = models.ForeignKey('Instanz', on_delete=models.CASCADE)
last_name = models.CharField(max_length=30)
first_name = models.CharField(max_length=30)
geburtsdatum = models.DateField()
It will raise the following exception. I dont get why it will search for a field named PROTECT. I used models.PROTECT in earlier migrations, before switching to CASCADE, but not any longer...
Operations to perform:
Apply all migrations: admin, auth, contenttypes, kundencenter, sessions
Running migrations:
Applying kundencenter.0001_initial...Traceback (most recent call last):
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\models\options.py", line 617, in get_field
return self.fields_map[field_name]
KeyError: 'PROTECT'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool\manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\core\management\__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\core\management\base.py", line 345, in execute
output = self.handle(*args, **options)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
fake_initial=fake_initial,
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\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 "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\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 "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\migrations\operations\models.py", line 96, in database_forwards
schema_editor.create_model(model)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\backends\base\schema.py", line 246, in create_model
definition, extra_params = self.column_sql(model, field)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\backends\base\schema.py", line 136, in column_sql
db_params = field.db_parameters(connection=self.connection)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\models\fields\related.py", line 940, in db_parameters
return {"type": self.db_type(connection), "check": self.db_check(connection)}
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\models\fields\related.py", line 937, in db_type
return self.target_field.rel_db_type(connection=connection)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\models\fields\related.py", line 855, in target_field
return self.foreign_related_fields[0]
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\models\fields\related.py", line 595, in foreign_related_fields
return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field)
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\models\fields\related.py", line 582, in related_fields
self._related_fields = self.resolve_related_fields()
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\models\fields\related.py", line 575, in resolve_related_fields
else self.remote_field.model._meta.get_field(to_field_name))
File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\models\options.py", line 619, in get_field
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: Instanz has no field named 'PROTECT'
Here's the deal: I messed up some earlier migrations that were blocking the process, because Djangos migrate uses all unaplied migrations.
I had to go to the folder \\migrations and delete all files (except init.py of course).
Everything works like a charm now.
If this happens in production, you would probably delete only the migrations to the point of the last working migration...

ResetDjango postgresql database? flush does not work

I have made changes to my model and tried to migrate the database using:
python3 manage.py makemigrations
python3 manage.py migrate
I got the following output:
vagrant#vagrant-ubuntu-trusty-64:/vagrant/grader$ python3 manage.py makemigrations
No changes detected
vagrant#vagrant-ubuntu-trusty-64:/vagrant/grader$ python3 manage.py migrate Operations to perform:
Apply all migrations: contenttypes, sessions, admin, auth, core
Running migrations:
Rendering model states... DONE
Applying core.0002_auto_20160103_0955...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.4/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/python3.4/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/python3.4/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/python3.4/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python3.4/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/python3.4/dist-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/schema.py", line 382, in add_field
definition, params = self.column_sql(model, field, include_default=True)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/schema.py", line 145, in column_sql
default_value = self.effective_default(field)
File "/usr/local/lib/python3.4/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/python3.4/dist-packages/django/db/models/fields/related.py", line 910, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/__init__.py", line 728, in get_db_prep_save
prepared=False)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/__init__.py", line 968, in get_db_prep_value
value = self.get_prep_value(value)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/__init__.py", line 976, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'
I don't know why the migration doesn't work. I can see that the cause is some kind of type error, but don't know what the cause is.
I figured that I would attempt to just clear the database completely as I have no relevant data in it. I planned to use:
python3 manage.py flush
python3 manage.py makemigrations
python3 manage.py migrate
But got the following output:
vagrant#vagrant-ubuntu-trusty-64:/vagrant/grader$ python3 manage.py flush
You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the 'graderdb' database,
and return each table to an empty state.
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: yes
CommandError: Database graderdb couldn't be flushed. Possible reasons:
* The database isn't running or isn't configured correctly.
* At least one of the expected database tables doesn't exist.
* The SQL was invalid.
Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run.
The full error: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "core_mark" references "core_student".
HINT: Truncate table "core_mark" at the same time, or use TRUNCATE ... CASCADE.
How can I completely reset a Django psql database?
As the message says, please run python3 manage.py sqlflush to see what SQL commands Django is trying to run.
Check that all tables used in the command exist in database.

Categories