I am trying to configure a project for pythonanywhere.com.
I deleted an old sqlite3 file, as well as migrations, so now I want to restore it. I launched command py manage.py makemigrations, then I run py manage.py migrate. But there I got an error:
Operations to perform:
Apply all migrations: FriendsAnalyzer, account, admin, auth, contenttypes, sessions, sites, socialaccount
Running migrations:
Applying socialaccount.0001_initial...Traceback (most recent call last):
File "/home/FarmerKarwer/VkAnalyzer/manage.py", line 22, in <module>
main()
File "/home/FarmerKarwer/VkAnalyzer/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute
output = self.handle(*args, **options)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 349, in handle
post_migrate_state = executor.migrate(
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 135, in migrate
state = self._migrate_all_forwards(
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards
state = self.apply_migration(
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 252, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/migration.py", line 130, in apply
operation.database_forwards(
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards
schema_editor.create_model(model)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 444, in create_model
sql, params = self.table_sql(model)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 216, in table_sql
definition, extra_params = self.column_sql(model, field)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 348, in column_sql
field_db_params = field.db_parameters(connection=self.connection)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/models/fields/related.py", line 1183, in db_parameters
target_db_parameters = self.target_field.db_parameters(connection)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/models/fields/related.py", line 1060, in target_field
return self.foreign_related_fields[0]
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/utils/functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/models/fields/related.py", line 747, in foreign_related_fields
rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/utils/functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/models/fields/related.py", line 734, in related_fields
return self.resolve_related_fields()
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/models/fields/related.py", line 1103, in resolve_related_fields
related_fields = super().resolve_related_fields()
File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/models/fields/related.py", line 712, in resolve_related_fields
raise ValueError(
ValueError: Related model 'auth.user' cannot be resolved
I don't think that the problem is in models.py because it worked well on my local computer. But here it is:
from django.db import models
from allauth.socialaccount.models import SocialAccount
# Create your models here.
class ResultInfo(models.Model):
uid = models.ForeignKey(SocialAccount, on_delete=models.CASCADE)
friend_id = models.CharField(max_length = 16)
status = models.BooleanField()
status_description = models.CharField(max_length = 16, null=True, blank=True)
result_info = models.JSONField()
def __str__(self):
return str(self.uid) + ", friend_id:" + self.friend_id
class Meta:
constraints = [
models.UniqueConstraint(fields=['uid', 'friend_id'], name='composite_key')
]
I thought that the problem may be in lack of superuser, so I tried to create one. However, I got another problem: User Registration with error: no such table: auth_user. I read the solution here and it states that I need to do python manage.py migrate. But it is impossible, as I said previously.
This is a strange behavior because I still have no sqlite file. And exactly the same problem exists WITH sqlite file. Please note that it is NOT duplicate of this question because I have different traceback, also I have much newer version of Django (4.1), as well as the site works normally on localhost.
You likely have a setting:
AUTH_USER_MODEL = 'auth.User'
so with a capital U. This will refer to the user model.
You probably did not migrate the auth model. You can do this first with:
python manage.py migrate auth
Related
models.py
This is the models.py file of my django project. I am getting this error in 5 line of the code below.I wanted to connect django default User model to my model by OneToOneField to provide multiple account functionality to my project. but I am stuck at this error that I don't understand.
plz, help.
from django.contrib.auth.models import User
# Create your models here.
class DailyTrack(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, related_name = 'Profile', default='')
income = models.IntegerField()
expense = models.IntegerField()
added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'Income {self.amount} Income {self.amount}'
error is in the 4th line at the default field, I tried removing default or adding it but I am unable to understand this.
There is an error for
Operations to perform:
Apply all migrations: admin, auth, contenttypes, dailytrackapp, sessions
Running migrations:
Applying dailytrackapp.0003_dailytrack_user...Traceback (most recent call last):
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'null'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\NIitin\Desktop\MultiProj\DailyTrack\manage.py", line 22, in <module>
main()
File "C:\Users\NIitin\Desktop\MultiProj\DailyTrack\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 371, in execute
output = self.handle(*args, **options)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\core\management\commands\migrate.py", line 243, in handle
post_migrate_state = executor.migrate(
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\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\NIitin\AppData\Roaming\Python\Python39\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\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\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\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards
schema_editor.add_field(
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add_field
self._remake_table(model, create_field=field)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\backends\sqlite3\schema.py", line 189, in _remake_table
self.effective_default(create_field)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\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 "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\related.py", line 971, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\__init__.py", line 823, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\__init__.py", line 2388, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\__init__.py", line 1776, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got 'null'.
NIitin#Nitin MINGW64 ~/Desktop/MultiProj/DailyTrack
$ python manage.py makemigrations
Migrations for 'dailytrackapp':
dailytrackapp\migrations\0001_initial.py
- Create model DailyTrack
NIitin#Nitin MINGW64 ~/Desktop/MultiProj/DailyTrack
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, content types, dailytrackapp, sessions
Running migrations:
No migrations to apply.```
Can somebody help me? plz, I need to fix this urgently.
I changed my DB backends from sqlite3 to postgre. When I try to run migrate I have an error
MacBook-Pro-Oleg:avtofarm okorablev$ python3 manage.py migrate
Operations to perform:
Synchronize unmigrated apps: messages, avtofarm, smart_selects, staticfiles, thumbnail
Apply all migrations: contenttypes, admin, callboard, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying callboard.0004_auto_20150701_1609...Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: column "manufdate" cannot be cast automatically to type date
HINT: Specify a USING expression to perform the conversion.
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "manage.py", line 10, in
execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/init.py",
line 338, in execute_from_command_line
utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/init.py",
line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/base.py",
line 393, in run_from_argv
self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/base.py",
line 444, in execute
output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/commands/migrate.py",
line 221, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File
"/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/executor.py",
line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File
"/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/executor.py",
line 148, in apply_migration
state = migration.apply(state, schema_editor) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/migration.py",
line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File
"/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/operations/fields.py",
line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/base/schema.py",
line 484, in alter_field
old_db_params, new_db_params, strict) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/base/schema.py",
line 636, in _alter_field
params, File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/base/schema.py",
line 111, in execute
cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py",
line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py",
line 64, in execute
return self.cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/utils.py",
line 97, in exit
six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/utils/six.py",
line 658, in reraise
raise value.with_traceback(tb) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py",
line 64, in execute
return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column "manufdate" cannot be cast
automatically to type date HINT: Specify a USING expression to
perform the conversion.
Model
class Zip(models.Model):
category = models.ForeignKey(Category,null=True,verbose_name='Категория')
subcategory = ChainedForeignKey(SubCategory,chained_field="category",
chained_model_field="category",
show_all=False,
auto_choose=True,verbose_name='Подкатегория')
type = models.ForeignKey(Type,verbose_name='Состояние')
zipgroup = models.ForeignKey(ZipGroup,null=True,verbose_name='Группа запчастей')
ziptype = models.ForeignKey(ZipType,null=True,verbose_name='Вид запчасти')
cartype = models.ForeignKey(CarType,null=True,verbose_name='Тип авто')
carmodel = models.ForeignKey(CarModel,null=True,verbose_name='Модель транспорта')
carbodytype = models.ForeignKey(CarBodyType,null=True,verbose_name='Тип кузова')
catalognumber = models.CharField(max_length=100,null=True,blank=True,verbose_name='Номер по каталогу')
manufdate = models.CharField(max_length=4,null=True,verbose_name='Год выпуска')
title = models.CharField(max_length=100,verbose_name='Заголовок объявления')
description = models.TextField(null=True,verbose_name='Описание')
price = models.IntegerField(verbose_name='Цена')
user = models.ForeignKey(User,verbose_name='Пользователь')
creation_date = models.DateTimeField('date published')
is_sell = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
likes = models.IntegerField(default=0)
Take a look into your migrations code (for application which contains Zip model). Looks like there is some issue with migrations, because you receive the error about date conversion, when in current model you have CharField type for manufdate column.
The problem was solved after I deleted database, made new database and one more time did makemigrations and migrate. But I think should be another way how you can decide this problem better without deleting database
I'm following the instructions to upgrade a Django app from Django 1.6.11 to 1.8.1. I've deleted all the migrations save for the init.py. I then run:
manage.py makemigrations
and it crashes with the following traceback:
Traceback (most recent call last):
File "manage.py", line 12, in <module>
execute_from_command_line(sys.argv)
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 143, in handle
self.write_migration_files(changes)
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 171, in write_migration_files
migration_string = writer.as_string()
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/db/migrations/writer.py", line 166, in as_string
operation_string, operation_imports = OperationWriter(operation).serialize()
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/db/migrations/writer.py", line 124, in serialize
_write(arg_name, arg_value)
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/db/migrations/writer.py", line 75, in _write
arg_string, arg_imports = MigrationWriter.serialize(item)
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/db/migrations/writer.py", line 303, in serialize
item_string, item_imports = cls.serialize(item)
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/db/migrations/writer.py", line 377, in serialize
return cls.serialize_deconstructed(path, args, kwargs)
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/db/migrations/writer.py", line 268, in serialize_deconstructed
arg_string, arg_imports = cls.serialize(arg)
File "/Users/dwatson/Environments/website/lib/python2.7/site-packages/django/db/migrations/writer.py", line 465, in serialize
"topics/migrations/#migration-serializing" % (value, get_docs_version())
ValueError: Cannot serialize: <bound method AccountManager.gen_num of <coreapi.models.AccountManager object at 0x103925450>>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/1.8/topics/migrations/#migration-serializing
This function is a method defined in the AccountManager class, which derives from models.Manager:
def gen_num(self):
max_digits = 9
candidate = random.randint(0, 10**max_digits)
return candidate
I've inspected the return candidate line and as expected, it's an int.
I assume that this method is being introspected because it is set as the default for the associated field:
num = models.PositiveIntegerField(
_('Num'), help_text=_('Number, automatically-generated'),
unique=True, blank=True, null=True, default=AccountManager().gen_num
)
The solution is to follow the advice given here:
https://docs.djangoproject.com/en/1.8/topics/migrations/#migration-serializing
That is, move the function from the class body of the Manager to the module body:
def gen_num():
max_digits = 9
candidate = random.randint(0, 10**max_digits)
return candidate
After this change, makemigrations completes successfully.
I add some new fields in model and django suggested me to add default value or set some default params in model. I added datetime object as value, but the value should be the int or number. Now I can't sync db becouse of type error. I tried to delete some objects which was instances of this model, where I did some changes but It doesn't help me.
How I can fix my model now?!
this is traceback
Applying card.0026_auto_20150104_1323...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\__init__.p
y", line 385, in execute_from_command_line
utility.execute()
File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\__init__.p
y", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 338, in execute
output = self.handle(*args, **options)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 533, in handle
return self.handle_noargs(**options)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\commands\s
yncdb.py", line 27, in handle_noargs
call_command("migrate", **options)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\__init__.p
y", line 115, in call_command
return klass.execute(*args, **defaults)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 338, in execute
output = self.handle(*args, **options)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\commands\m
igrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\executor.py"
, line 63, in migrate
self.apply_migration(migration, fake=fake)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\executor.py"
, line 97, in apply_migration
migration.apply(project_state, schema_editor)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\migration.py
", line 107, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, ne
w_state)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\operations\f
ields.py", line 37, in database_forwards
field,
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\backends\sqlite3\schema
.py", line 167, in add_field
self._remake_table(model, create_fields=[field])
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\backends\sqlite3\schema
.py", line 74, in _remake_table
self.effective_default(field)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\backends\schema.py", li
ne 184, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\related.p
y", line 1735, in get_db_prep_save
return self.related_field.get_db_prep_save(value, connection=connection)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\__init__.
py", line 627, in get_db_prep_save
prepared=False)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\__init__.
py", line 907, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\__init__.
py", line 915, in get_prep_value
return int(value)
TypeError: int() argument must be a string or a number, not 'datetime.datetime'
this is part of model code:
I added owner field in CollectionItem object:
class CollectionItem (models.Model):
card = models.ForeignKey(Card)
golden = models.BooleanField(default=False)
count = models.IntegerField(default=0)
level = models.IntegerField(default=1)
owner = models.ForeignKey(User, related_name='collectionCards')
#property
def price(self):
return self.card.price
class Collection (models.Model):
owner = models.ForeignKey(User, related_name='collections')
items = models.ManyToManyField(CollectionItem, through='CollectionCollector')
class CollectionAdmin (admin.ModelAdmin):
fields = ['owner'] admin.site.register(Collection, CollectionAdmin)
class CollectionCollector (models.Model):
item = models.ForeignKey(CollectionItem, related_name='collection_item')
collection = models.ForeignKey(Collection)
I think, you gave datetime.datetime.now() as default values during migrations as it asked you to enter.
just edit the migration files and change the datetime default value to string for one of these fields
count = models.IntegerField(default=0)
level = models.IntegerField(default=1)
then run migrate again
I face the same sitution in my enviroment , and here are the solutions what i take:
remove db.sqlite3
remove all migrations file in all app
then rerun comments:
python manage.py makemigrations
python manage.py migrate
After these steps,no error appears again.
I also find a similar solution link in https://stackoverflow.com/a/34825277/6711680
Delete the old python files in migration folder in your app directory and then migrate again. It will fix the issues.
I have a big issue here, I just cannot migrate my database as I want. I test a lot of things (even write directly in database...). It runs with Django 1.7.1 and my database is store with Sqlite3. So here's my issue:
I have a model like this:
from django.db import models
import datetime
class UserUsingTime(models.Model):
userid = models.CharField(max_length = 30)
using_time = models.DateTimeField(default = datetime.time())
(The thing that I want to do is to store a timer. Like maybe all times in a race for example.)
And I add this line at the end of my model:
app_name = models.CharField(max_length = 20, null = True)
Then I run python manage makemigrations my_app_name and it results:
Migrations for 'my_app_name':
0003_userusingtime_app_name.py:
- Add field app_name to userusingtime
So for now all is good :) But when I try to run python manage migrate then I have tons of errors lines stuff:
Operations to perform:
Apply all migrations: admin, contenttypes, my_app_name, auth, sessions
Running migrations:
Applying my_app_name.0003_userusingtime_app_name...Traceback (most recent call last):
File "./manage.py", line 8, in
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, 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 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 63, in migrate
self.apply_migration(migration, fake=fake)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 97, in apply_migration
migration.apply(project_state, schema_editor)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 107, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 37, in database_forwards
field,
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 167, 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 128, in _remake_table
self.create_model(temp_model)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 209, in create_model
definition, extra_params = self.column_sql(model, field)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 121, in column_sql
default_value = self.effective_default(field)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 184, 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 627, in get_db_prep_save
prepared=False)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1286, 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 1269, in get_prep_value
value = super(DateTimeField, self).get_prep_value(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1171, in get_prep_value
return self.to_python(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1228, in to_python
parsed = parse_datetime(value)
File "/usr/local/lib/python2.7/dist-packages/django/utils/dateparse.py", line 70, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or buffer
So I really don't know what to do next... Plus it seems there is a datetime errors and I can't explain that because I did not touch any datetime object in my models... So weird!
Please help me out with this issue :)
I thank you in advance guys (Y) !
Your using_time field definition is faulty. Django is complaining because you're trying to store a time object in a datetime container.
DateTimeField is simply the wrong kind of field for what you're trying to represent (a length of time). You could switch this to a TimeField, or simply use a FloatField or IntegerField to store the seconds or milliseconds.
(Why is this only throwing a migrations error now? I assume it's because this bug wasn't caught in an earlier version of Django, and this is the first real migration (i.e. not the initial, fake migration) that you've tried in 1.7.)